blob: a7e13cc4af98ad3bb50b0c91dea687f66bb57729 [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
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080019import com.android.internal.R;
20import com.android.internal.util.Predicate;
21import com.android.internal.view.menu.MenuBuilder;
22
Christopher Tatea53146c2010-09-07 11:57:52 -070023import android.content.ClipData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080025import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.res.Resources;
27import android.content.res.TypedArray;
28import android.graphics.Bitmap;
Adam Powell2b342f02010-08-18 18:14:13 -070029import android.graphics.Camera;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.graphics.Canvas;
Mike Cleronf116bf82009-09-27 19:14:12 -070031import android.graphics.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.graphics.LinearGradient;
33import android.graphics.Matrix;
34import android.graphics.Paint;
35import android.graphics.PixelFormat;
svetoslavganov75986cf2009-05-14 22:28:01 -070036import android.graphics.Point;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.graphics.PorterDuff;
38import android.graphics.PorterDuffXfermode;
39import android.graphics.Rect;
Adam Powell6e346362010-07-23 10:18:23 -070040import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.graphics.Region;
42import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.graphics.drawable.ColorDrawable;
44import android.graphics.drawable.Drawable;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Message;
48import android.os.Parcel;
49import android.os.Parcelable;
50import android.os.RemoteException;
51import android.os.SystemClock;
52import android.os.SystemProperties;
53import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070055import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070056import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070057import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070058import android.util.Pools;
59import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.ContextMenu.ContextMenuInfo;
svetoslavganov75986cf2009-05-14 22:28:01 -070061import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070065import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070066import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.view.inputmethod.InputConnection;
68import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.widget.ScrollBarDrawable;
70
Christopher Tatea0374192010-10-05 13:06:41 -070071import java.lang.ref.WeakReference;
svetoslavganov75986cf2009-05-14 22:28:01 -070072import java.lang.reflect.InvocationTargetException;
73import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import java.util.ArrayList;
75import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070076import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070077import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
79/**
80 * <p>
81 * This class represents the basic building block for user interface components. A View
82 * occupies a rectangular area on the screen and is responsible for drawing and
83 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070084 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
86 * are invisible containers that hold other Views (or other ViewGroups) and define
87 * their layout properties.
88 * </p>
89 *
90 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070091 * <p>For an introduction to using this class to develop your
92 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070094 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
102 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
103 * </p>
104 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700105 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 * <a name="Using"></a>
107 * <h3>Using Views</h3>
108 * <p>
109 * All of the views in a window are arranged in a single tree. You can add views
110 * either from code or by specifying a tree of views in one or more XML layout
111 * files. There are many specialized subclasses of views that act as controls or
112 * are capable of displaying text, images, or other content.
113 * </p>
114 * <p>
115 * Once you have created a tree of views, there are typically a few types of
116 * common operations you may wish to perform:
117 * <ul>
118 * <li><strong>Set properties:</strong> for example setting the text of a
119 * {@link android.widget.TextView}. The available properties and the methods
120 * that set them will vary among the different subclasses of views. Note that
121 * properties that are known at build time can be set in the XML layout
122 * files.</li>
123 * <li><strong>Set focus:</strong> The framework will handled moving focus in
124 * response to user input. To force focus to a specific view, call
125 * {@link #requestFocus}.</li>
126 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
127 * that will be notified when something interesting happens to the view. For
128 * example, all views will let you set a listener to be notified when the view
129 * gains or loses focus. You can register such a listener using
130 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
131 * specialized listeners. For example, a Button exposes a listener to notify
132 * clients when the button is clicked.</li>
133 * <li><strong>Set visibility:</strong> You can hide or show views using
134 * {@link #setVisibility}.</li>
135 * </ul>
136 * </p>
137 * <p><em>
138 * Note: The Android framework is responsible for measuring, laying out and
139 * drawing views. You should not call methods that perform these actions on
140 * views yourself unless you are actually implementing a
141 * {@link android.view.ViewGroup}.
142 * </em></p>
143 *
144 * <a name="Lifecycle"></a>
145 * <h3>Implementing a Custom View</h3>
146 *
147 * <p>
148 * To implement a custom view, you will usually begin by providing overrides for
149 * some of the standard methods that the framework calls on all views. You do
150 * not need to override all of these methods. In fact, you can start by just
151 * overriding {@link #onDraw(android.graphics.Canvas)}.
152 * <table border="2" width="85%" align="center" cellpadding="5">
153 * <thead>
154 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
155 * </thead>
156 *
157 * <tbody>
158 * <tr>
159 * <td rowspan="2">Creation</td>
160 * <td>Constructors</td>
161 * <td>There is a form of the constructor that are called when the view
162 * is created from code and a form that is called when the view is
163 * inflated from a layout file. The second form should parse and apply
164 * any attributes defined in the layout file.
165 * </td>
166 * </tr>
167 * <tr>
168 * <td><code>{@link #onFinishInflate()}</code></td>
169 * <td>Called after a view and all of its children has been inflated
170 * from XML.</td>
171 * </tr>
172 *
173 * <tr>
174 * <td rowspan="3">Layout</td>
175 * <td><code>{@link #onMeasure}</code></td>
176 * <td>Called to determine the size requirements for this view and all
177 * of its children.
178 * </td>
179 * </tr>
180 * <tr>
181 * <td><code>{@link #onLayout}</code></td>
182 * <td>Called when this view should assign a size and position to all
183 * of its children.
184 * </td>
185 * </tr>
186 * <tr>
187 * <td><code>{@link #onSizeChanged}</code></td>
188 * <td>Called when the size of this view has changed.
189 * </td>
190 * </tr>
191 *
192 * <tr>
193 * <td>Drawing</td>
194 * <td><code>{@link #onDraw}</code></td>
195 * <td>Called when the view should render its content.
196 * </td>
197 * </tr>
198 *
199 * <tr>
200 * <td rowspan="4">Event processing</td>
201 * <td><code>{@link #onKeyDown}</code></td>
202 * <td>Called when a new key event occurs.
203 * </td>
204 * </tr>
205 * <tr>
206 * <td><code>{@link #onKeyUp}</code></td>
207 * <td>Called when a key up event occurs.
208 * </td>
209 * </tr>
210 * <tr>
211 * <td><code>{@link #onTrackballEvent}</code></td>
212 * <td>Called when a trackball motion event occurs.
213 * </td>
214 * </tr>
215 * <tr>
216 * <td><code>{@link #onTouchEvent}</code></td>
217 * <td>Called when a touch screen motion event occurs.
218 * </td>
219 * </tr>
220 *
221 * <tr>
222 * <td rowspan="2">Focus</td>
223 * <td><code>{@link #onFocusChanged}</code></td>
224 * <td>Called when the view gains or loses focus.
225 * </td>
226 * </tr>
227 *
228 * <tr>
229 * <td><code>{@link #onWindowFocusChanged}</code></td>
230 * <td>Called when the window containing the view gains or loses focus.
231 * </td>
232 * </tr>
233 *
234 * <tr>
235 * <td rowspan="3">Attaching</td>
236 * <td><code>{@link #onAttachedToWindow()}</code></td>
237 * <td>Called when the view is attached to a window.
238 * </td>
239 * </tr>
240 *
241 * <tr>
242 * <td><code>{@link #onDetachedFromWindow}</code></td>
243 * <td>Called when the view is detached from its window.
244 * </td>
245 * </tr>
246 *
247 * <tr>
248 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
249 * <td>Called when the visibility of the window containing the view
250 * has changed.
251 * </td>
252 * </tr>
253 * </tbody>
254 *
255 * </table>
256 * </p>
257 *
258 * <a name="IDs"></a>
259 * <h3>IDs</h3>
260 * Views may have an integer id associated with them. These ids are typically
261 * assigned in the layout XML files, and are used to find specific views within
262 * the view tree. A common pattern is to:
263 * <ul>
264 * <li>Define a Button in the layout file and assign it a unique ID.
265 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700266 * &lt;Button
267 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 * android:layout_width="wrap_content"
269 * android:layout_height="wrap_content"
270 * android:text="@string/my_button_text"/&gt;
271 * </pre></li>
272 * <li>From the onCreate method of an Activity, find the Button
273 * <pre class="prettyprint">
274 * Button myButton = (Button) findViewById(R.id.my_button);
275 * </pre></li>
276 * </ul>
277 * <p>
278 * View IDs need not be unique throughout the tree, but it is good practice to
279 * ensure that they are at least unique within the part of the tree you are
280 * searching.
281 * </p>
282 *
283 * <a name="Position"></a>
284 * <h3>Position</h3>
285 * <p>
286 * The geometry of a view is that of a rectangle. A view has a location,
287 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
288 * two dimensions, expressed as a width and a height. The unit for location
289 * and dimensions is the pixel.
290 * </p>
291 *
292 * <p>
293 * It is possible to retrieve the location of a view by invoking the methods
294 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
295 * coordinate of the rectangle representing the view. The latter returns the
296 * top, or Y, coordinate of the rectangle representing the view. These methods
297 * both return the location of the view relative to its parent. For instance,
298 * when getLeft() returns 20, that means the view is located 20 pixels to the
299 * right of the left edge of its direct parent.
300 * </p>
301 *
302 * <p>
303 * In addition, several convenience methods are offered to avoid unnecessary
304 * computations, namely {@link #getRight()} and {@link #getBottom()}.
305 * These methods return the coordinates of the right and bottom edges of the
306 * rectangle representing the view. For instance, calling {@link #getRight()}
307 * is similar to the following computation: <code>getLeft() + getWidth()</code>
308 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
309 * </p>
310 *
311 * <a name="SizePaddingMargins"></a>
312 * <h3>Size, padding and margins</h3>
313 * <p>
314 * The size of a view is expressed with a width and a height. A view actually
315 * possess two pairs of width and height values.
316 * </p>
317 *
318 * <p>
319 * The first pair is known as <em>measured width</em> and
320 * <em>measured height</em>. These dimensions define how big a view wants to be
321 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
322 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
323 * and {@link #getMeasuredHeight()}.
324 * </p>
325 *
326 * <p>
327 * The second pair is simply known as <em>width</em> and <em>height</em>, or
328 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
329 * dimensions define the actual size of the view on screen, at drawing time and
330 * after layout. These values may, but do not have to, be different from the
331 * measured width and height. The width and height can be obtained by calling
332 * {@link #getWidth()} and {@link #getHeight()}.
333 * </p>
334 *
335 * <p>
336 * To measure its dimensions, a view takes into account its padding. The padding
337 * is expressed in pixels for the left, top, right and bottom parts of the view.
338 * Padding can be used to offset the content of the view by a specific amount of
339 * pixels. For instance, a left padding of 2 will push the view's content by
340 * 2 pixels to the right of the left edge. Padding can be set using the
341 * {@link #setPadding(int, int, int, int)} method and queried by calling
342 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
343 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
344 * </p>
345 *
346 * <p>
347 * Even though a view can define a padding, it does not provide any support for
348 * margins. However, view groups provide such a support. Refer to
349 * {@link android.view.ViewGroup} and
350 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
351 * </p>
352 *
353 * <a name="Layout"></a>
354 * <h3>Layout</h3>
355 * <p>
356 * Layout is a two pass process: a measure pass and a layout pass. The measuring
357 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
358 * of the view tree. Each view pushes dimension specifications down the tree
359 * during the recursion. At the end of the measure pass, every view has stored
360 * its measurements. The second pass happens in
361 * {@link #layout(int,int,int,int)} and is also top-down. During
362 * this pass each parent is responsible for positioning all of its children
363 * using the sizes computed in the measure pass.
364 * </p>
365 *
366 * <p>
367 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
368 * {@link #getMeasuredHeight()} values must be set, along with those for all of
369 * that view's descendants. A view's measured width and measured height values
370 * must respect the constraints imposed by the view's parents. This guarantees
371 * that at the end of the measure pass, all parents accept all of their
372 * children's measurements. A parent view may call measure() more than once on
373 * its children. For example, the parent may measure each child once with
374 * unspecified dimensions to find out how big they want to be, then call
375 * measure() on them again with actual numbers if the sum of all the children's
376 * unconstrained sizes is too big or too small.
377 * </p>
378 *
379 * <p>
380 * The measure pass uses two classes to communicate dimensions. The
381 * {@link MeasureSpec} class is used by views to tell their parents how they
382 * want to be measured and positioned. The base LayoutParams class just
383 * describes how big the view wants to be for both width and height. For each
384 * dimension, it can specify one of:
385 * <ul>
386 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800387 * <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 -0800388 * (minus padding)
389 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
390 * enclose its content (plus padding).
391 * </ul>
392 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
393 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
394 * an X and Y value.
395 * </p>
396 *
397 * <p>
398 * MeasureSpecs are used to push requirements down the tree from parent to
399 * child. A MeasureSpec can be in one of three modes:
400 * <ul>
401 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
402 * of a child view. For example, a LinearLayout may call measure() on its child
403 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
404 * tall the child view wants to be given a width of 240 pixels.
405 * <li>EXACTLY: This is used by the parent to impose an exact size on the
406 * child. The child must use this size, and guarantee that all of its
407 * descendants will fit within this size.
408 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
409 * child. The child must gurantee that it and all of its descendants will fit
410 * within this size.
411 * </ul>
412 * </p>
413 *
414 * <p>
415 * To intiate a layout, call {@link #requestLayout}. This method is typically
416 * called by a view on itself when it believes that is can no longer fit within
417 * its current bounds.
418 * </p>
419 *
420 * <a name="Drawing"></a>
421 * <h3>Drawing</h3>
422 * <p>
423 * Drawing is handled by walking the tree and rendering each view that
424 * intersects the the invalid region. Because the tree is traversed in-order,
425 * this means that parents will draw before (i.e., behind) their children, with
426 * siblings drawn in the order they appear in the tree.
427 * If you set a background drawable for a View, then the View will draw it for you
428 * before calling back to its <code>onDraw()</code> method.
429 * </p>
430 *
431 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700432 * 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 -0800433 * </p>
434 *
435 * <p>
436 * To force a view to draw, call {@link #invalidate()}.
437 * </p>
438 *
439 * <a name="EventHandlingThreading"></a>
440 * <h3>Event Handling and Threading</h3>
441 * <p>
442 * The basic cycle of a view is as follows:
443 * <ol>
444 * <li>An event comes in and is dispatched to the appropriate view. The view
445 * handles the event and notifies any listeners.</li>
446 * <li>If in the course of processing the event, the view's bounds may need
447 * to be changed, the view will call {@link #requestLayout()}.</li>
448 * <li>Similarly, if in the course of processing the event the view's appearance
449 * may need to be changed, the view will call {@link #invalidate()}.</li>
450 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
451 * the framework will take care of measuring, laying out, and drawing the tree
452 * as appropriate.</li>
453 * </ol>
454 * </p>
455 *
456 * <p><em>Note: The entire view tree is single threaded. You must always be on
457 * the UI thread when calling any method on any view.</em>
458 * If you are doing work on other threads and want to update the state of a view
459 * from that thread, you should use a {@link Handler}.
460 * </p>
461 *
462 * <a name="FocusHandling"></a>
463 * <h3>Focus Handling</h3>
464 * <p>
465 * The framework will handle routine focus movement in response to user input.
466 * This includes changing the focus as views are removed or hidden, or as new
467 * views become available. Views indicate their willingness to take focus
468 * through the {@link #isFocusable} method. To change whether a view can take
469 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
470 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
471 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
472 * </p>
473 * <p>
474 * Focus movement is based on an algorithm which finds the nearest neighbor in a
475 * given direction. In rare cases, the default algorithm may not match the
476 * intended behavior of the developer. In these situations, you can provide
477 * explicit overrides by using these XML attributes in the layout file:
478 * <pre>
479 * nextFocusDown
480 * nextFocusLeft
481 * nextFocusRight
482 * nextFocusUp
483 * </pre>
484 * </p>
485 *
486 *
487 * <p>
488 * To get a particular view to take focus, call {@link #requestFocus()}.
489 * </p>
490 *
491 * <a name="TouchMode"></a>
492 * <h3>Touch Mode</h3>
493 * <p>
494 * When a user is navigating a user interface via directional keys such as a D-pad, it is
495 * necessary to give focus to actionable items such as buttons so the user can see
496 * what will take input. If the device has touch capabilities, however, and the user
497 * begins interacting with the interface by touching it, it is no longer necessary to
498 * always highlight, or give focus to, a particular view. This motivates a mode
499 * for interaction named 'touch mode'.
500 * </p>
501 * <p>
502 * For a touch capable device, once the user touches the screen, the device
503 * will enter touch mode. From this point onward, only views for which
504 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
505 * Other views that are touchable, like buttons, will not take focus when touched; they will
506 * only fire the on click listeners.
507 * </p>
508 * <p>
509 * Any time a user hits a directional key, such as a D-pad direction, the view device will
510 * exit touch mode, and find a view to take focus, so that the user may resume interacting
511 * with the user interface without touching the screen again.
512 * </p>
513 * <p>
514 * The touch mode state is maintained across {@link android.app.Activity}s. Call
515 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
516 * </p>
517 *
518 * <a name="Scrolling"></a>
519 * <h3>Scrolling</h3>
520 * <p>
521 * The framework provides basic support for views that wish to internally
522 * scroll their content. This includes keeping track of the X and Y scroll
523 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700524 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
525 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 * </p>
527 *
528 * <a name="Tags"></a>
529 * <h3>Tags</h3>
530 * <p>
531 * Unlike IDs, tags are not used to identify views. Tags are essentially an
532 * extra piece of information that can be associated with a view. They are most
533 * often used as a convenience to store data related to views in the views
534 * themselves rather than by putting them in a separate structure.
535 * </p>
536 *
537 * <a name="Animation"></a>
538 * <h3>Animation</h3>
539 * <p>
540 * You can attach an {@link Animation} object to a view using
541 * {@link #setAnimation(Animation)} or
542 * {@link #startAnimation(Animation)}. The animation can alter the scale,
543 * rotation, translation and alpha of a view over time. If the animation is
544 * attached to a view that has children, the animation will affect the entire
545 * subtree rooted by that node. When an animation is started, the framework will
546 * take care of redrawing the appropriate views until the animation completes.
547 * </p>
Romain Guy171c5922011-01-06 10:04:23 -0800548 * <p>
549 * Starting with Android 3.0, the preferred way of animating views is to use the
550 * {@link android.animation} package APIs.
551 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 *
Jeff Brown85a31762010-09-01 17:01:00 -0700553 * <a name="Security"></a>
554 * <h3>Security</h3>
555 * <p>
556 * Sometimes it is essential that an application be able to verify that an action
557 * is being performed with the full knowledge and consent of the user, such as
558 * granting a permission request, making a purchase or clicking on an advertisement.
559 * Unfortunately, a malicious application could try to spoof the user into
560 * performing these actions, unaware, by concealing the intended purpose of the view.
561 * As a remedy, the framework offers a touch filtering mechanism that can be used to
562 * improve the security of views that provide access to sensitive functionality.
563 * </p><p>
564 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
Jeff Brown49ed71d2010-12-06 17:13:33 -0800565 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework
Jeff Brown85a31762010-09-01 17:01:00 -0700566 * will discard touches that are received whenever the view's window is obscured by
567 * another visible window. As a result, the view will not receive touches whenever a
568 * toast, dialog or other window appears above the view's window.
569 * </p><p>
570 * For more fine-grained control over security, consider overriding the
571 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
572 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
573 * </p>
574 *
Romain Guy171c5922011-01-06 10:04:23 -0800575 * @attr ref android.R.styleable#View_alpha
Romain Guyd6a463a2009-05-21 23:10:10 -0700576 * @attr ref android.R.styleable#View_background
577 * @attr ref android.R.styleable#View_clickable
578 * @attr ref android.R.styleable#View_contentDescription
579 * @attr ref android.R.styleable#View_drawingCacheQuality
580 * @attr ref android.R.styleable#View_duplicateParentState
581 * @attr ref android.R.styleable#View_id
582 * @attr ref android.R.styleable#View_fadingEdge
583 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700584 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700586 * @attr ref android.R.styleable#View_isScrollContainer
587 * @attr ref android.R.styleable#View_focusable
588 * @attr ref android.R.styleable#View_focusableInTouchMode
589 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
590 * @attr ref android.R.styleable#View_keepScreenOn
Romain Guy171c5922011-01-06 10:04:23 -0800591 * @attr ref android.R.styleable#View_layerType
Romain Guyd6a463a2009-05-21 23:10:10 -0700592 * @attr ref android.R.styleable#View_longClickable
593 * @attr ref android.R.styleable#View_minHeight
594 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 * @attr ref android.R.styleable#View_nextFocusDown
596 * @attr ref android.R.styleable#View_nextFocusLeft
597 * @attr ref android.R.styleable#View_nextFocusRight
598 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700599 * @attr ref android.R.styleable#View_onClick
600 * @attr ref android.R.styleable#View_padding
601 * @attr ref android.R.styleable#View_paddingBottom
602 * @attr ref android.R.styleable#View_paddingLeft
603 * @attr ref android.R.styleable#View_paddingRight
604 * @attr ref android.R.styleable#View_paddingTop
605 * @attr ref android.R.styleable#View_saveEnabled
Chet Haase73066682010-11-29 15:55:32 -0800606 * @attr ref android.R.styleable#View_rotation
607 * @attr ref android.R.styleable#View_rotationX
608 * @attr ref android.R.styleable#View_rotationY
609 * @attr ref android.R.styleable#View_scaleX
610 * @attr ref android.R.styleable#View_scaleY
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 * @attr ref android.R.styleable#View_scrollX
612 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700613 * @attr ref android.R.styleable#View_scrollbarSize
614 * @attr ref android.R.styleable#View_scrollbarStyle
615 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700616 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
617 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
619 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 * @attr ref android.R.styleable#View_scrollbarThumbVertical
621 * @attr ref android.R.styleable#View_scrollbarTrackVertical
622 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700624 * @attr ref android.R.styleable#View_soundEffectsEnabled
625 * @attr ref android.R.styleable#View_tag
Chet Haase73066682010-11-29 15:55:32 -0800626 * @attr ref android.R.styleable#View_transformPivotX
627 * @attr ref android.R.styleable#View_transformPivotY
628 * @attr ref android.R.styleable#View_translationX
629 * @attr ref android.R.styleable#View_translationY
Romain Guyd6a463a2009-05-21 23:10:10 -0700630 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 *
632 * @see android.view.ViewGroup
633 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700634public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 private static final boolean DBG = false;
636
637 /**
638 * The logging tag used by this class with android.util.Log.
639 */
640 protected static final String VIEW_LOG_TAG = "View";
641
642 /**
643 * Used to mark a View that has no ID.
644 */
645 public static final int NO_ID = -1;
646
647 /**
648 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
649 * calling setFlags.
650 */
651 private static final int NOT_FOCUSABLE = 0x00000000;
652
653 /**
654 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
655 * setFlags.
656 */
657 private static final int FOCUSABLE = 0x00000001;
658
659 /**
660 * Mask for use with setFlags indicating bits used for focus.
661 */
662 private static final int FOCUSABLE_MASK = 0x00000001;
663
664 /**
665 * This view will adjust its padding to fit sytem windows (e.g. status bar)
666 */
667 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
668
669 /**
670 * This view is visible. Use with {@link #setVisibility}.
671 */
672 public static final int VISIBLE = 0x00000000;
673
674 /**
675 * This view is invisible, but it still takes up space for layout purposes.
676 * Use with {@link #setVisibility}.
677 */
678 public static final int INVISIBLE = 0x00000004;
679
680 /**
681 * This view is invisible, and it doesn't take any space for layout
682 * purposes. Use with {@link #setVisibility}.
683 */
684 public static final int GONE = 0x00000008;
685
686 /**
687 * Mask for use with setFlags indicating bits used for visibility.
688 * {@hide}
689 */
690 static final int VISIBILITY_MASK = 0x0000000C;
691
692 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
693
694 /**
695 * This view is enabled. Intrepretation varies by subclass.
696 * Use with ENABLED_MASK when calling setFlags.
697 * {@hide}
698 */
699 static final int ENABLED = 0x00000000;
700
701 /**
702 * This view is disabled. Intrepretation varies by subclass.
703 * Use with ENABLED_MASK when calling setFlags.
704 * {@hide}
705 */
706 static final int DISABLED = 0x00000020;
707
708 /**
709 * Mask for use with setFlags indicating bits used for indicating whether
710 * this view is enabled
711 * {@hide}
712 */
713 static final int ENABLED_MASK = 0x00000020;
714
715 /**
716 * This view won't draw. {@link #onDraw} won't be called and further
717 * optimizations
718 * will be performed. It is okay to have this flag set and a background.
719 * Use with DRAW_MASK when calling setFlags.
720 * {@hide}
721 */
722 static final int WILL_NOT_DRAW = 0x00000080;
723
724 /**
725 * Mask for use with setFlags indicating bits used for indicating whether
726 * this view is will draw
727 * {@hide}
728 */
729 static final int DRAW_MASK = 0x00000080;
730
731 /**
732 * <p>This view doesn't show scrollbars.</p>
733 * {@hide}
734 */
735 static final int SCROLLBARS_NONE = 0x00000000;
736
737 /**
738 * <p>This view shows horizontal scrollbars.</p>
739 * {@hide}
740 */
741 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
742
743 /**
744 * <p>This view shows vertical scrollbars.</p>
745 * {@hide}
746 */
747 static final int SCROLLBARS_VERTICAL = 0x00000200;
748
749 /**
750 * <p>Mask for use with setFlags indicating bits used for indicating which
751 * scrollbars are enabled.</p>
752 * {@hide}
753 */
754 static final int SCROLLBARS_MASK = 0x00000300;
755
Jeff Brown85a31762010-09-01 17:01:00 -0700756 /**
757 * Indicates that the view should filter touches when its window is obscured.
758 * Refer to the class comments for more information about this security feature.
759 * {@hide}
760 */
761 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
762
763 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764
765 /**
766 * <p>This view doesn't show fading edges.</p>
767 * {@hide}
768 */
769 static final int FADING_EDGE_NONE = 0x00000000;
770
771 /**
772 * <p>This view shows horizontal fading edges.</p>
773 * {@hide}
774 */
775 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
776
777 /**
778 * <p>This view shows vertical fading edges.</p>
779 * {@hide}
780 */
781 static final int FADING_EDGE_VERTICAL = 0x00002000;
782
783 /**
784 * <p>Mask for use with setFlags indicating bits used for indicating which
785 * fading edges are enabled.</p>
786 * {@hide}
787 */
788 static final int FADING_EDGE_MASK = 0x00003000;
789
790 /**
791 * <p>Indicates this view can be clicked. When clickable, a View reacts
792 * to clicks by notifying the OnClickListener.<p>
793 * {@hide}
794 */
795 static final int CLICKABLE = 0x00004000;
796
797 /**
798 * <p>Indicates this view is caching its drawing into a bitmap.</p>
799 * {@hide}
800 */
801 static final int DRAWING_CACHE_ENABLED = 0x00008000;
802
803 /**
804 * <p>Indicates that no icicle should be saved for this view.<p>
805 * {@hide}
806 */
807 static final int SAVE_DISABLED = 0x000010000;
808
809 /**
810 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
811 * property.</p>
812 * {@hide}
813 */
814 static final int SAVE_DISABLED_MASK = 0x000010000;
815
816 /**
817 * <p>Indicates that no drawing cache should ever be created for this view.<p>
818 * {@hide}
819 */
820 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
821
822 /**
823 * <p>Indicates this view can take / keep focus when int touch mode.</p>
824 * {@hide}
825 */
826 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
827
828 /**
829 * <p>Enables low quality mode for the drawing cache.</p>
830 */
831 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
832
833 /**
834 * <p>Enables high quality mode for the drawing cache.</p>
835 */
836 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
837
838 /**
839 * <p>Enables automatic quality mode for the drawing cache.</p>
840 */
841 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
842
843 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
844 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
845 };
846
847 /**
848 * <p>Mask for use with setFlags indicating bits used for the cache
849 * quality property.</p>
850 * {@hide}
851 */
852 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
853
854 /**
855 * <p>
856 * Indicates this view can be long clicked. When long clickable, a View
857 * reacts to long clicks by notifying the OnLongClickListener or showing a
858 * context menu.
859 * </p>
860 * {@hide}
861 */
862 static final int LONG_CLICKABLE = 0x00200000;
863
864 /**
865 * <p>Indicates that this view gets its drawable states from its direct parent
866 * and ignores its original internal states.</p>
867 *
868 * @hide
869 */
870 static final int DUPLICATE_PARENT_STATE = 0x00400000;
871
872 /**
873 * The scrollbar style to display the scrollbars inside the content area,
874 * without increasing the padding. The scrollbars will be overlaid with
875 * translucency on the view's content.
876 */
877 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
878
879 /**
880 * The scrollbar style to display the scrollbars inside the padded area,
881 * increasing the padding of the view. The scrollbars will not overlap the
882 * content area of the view.
883 */
884 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
885
886 /**
887 * The scrollbar style to display the scrollbars at the edge of the view,
888 * without increasing the padding. The scrollbars will be overlaid with
889 * translucency.
890 */
891 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
892
893 /**
894 * The scrollbar style to display the scrollbars at the edge of the view,
895 * increasing the padding of the view. The scrollbars will only overlap the
896 * background, if any.
897 */
898 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
899
900 /**
901 * Mask to check if the scrollbar style is overlay or inset.
902 * {@hide}
903 */
904 static final int SCROLLBARS_INSET_MASK = 0x01000000;
905
906 /**
907 * Mask to check if the scrollbar style is inside or outside.
908 * {@hide}
909 */
910 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
911
912 /**
913 * Mask for scrollbar style.
914 * {@hide}
915 */
916 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
917
918 /**
919 * View flag indicating that the screen should remain on while the
920 * window containing this view is visible to the user. This effectively
921 * takes care of automatically setting the WindowManager's
922 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
923 */
924 public static final int KEEP_SCREEN_ON = 0x04000000;
925
926 /**
927 * View flag indicating whether this view should have sound effects enabled
928 * for events such as clicking and touching.
929 */
930 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
931
932 /**
933 * View flag indicating whether this view should have haptic feedback
934 * enabled for events such as long presses.
935 */
936 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
937
938 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700939 * <p>Indicates that the view hierarchy should stop saving state when
940 * it reaches this view. If state saving is initiated immediately at
941 * the view, it will be allowed.
942 * {@hide}
943 */
944 static final int PARENT_SAVE_DISABLED = 0x20000000;
945
946 /**
947 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
948 * {@hide}
949 */
950 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
951
952 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700953 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
954 * should add all focusable Views regardless if they are focusable in touch mode.
955 */
956 public static final int FOCUSABLES_ALL = 0x00000000;
957
958 /**
959 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
960 * should add only Views focusable in touch mode.
961 */
962 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
963
964 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 * Use with {@link #focusSearch}. Move focus to the previous selectable
966 * item.
967 */
968 public static final int FOCUS_BACKWARD = 0x00000001;
969
970 /**
971 * Use with {@link #focusSearch}. Move focus to the next selectable
972 * item.
973 */
974 public static final int FOCUS_FORWARD = 0x00000002;
975
976 /**
977 * Use with {@link #focusSearch}. Move focus to the left.
978 */
979 public static final int FOCUS_LEFT = 0x00000011;
980
981 /**
982 * Use with {@link #focusSearch}. Move focus up.
983 */
984 public static final int FOCUS_UP = 0x00000021;
985
986 /**
987 * Use with {@link #focusSearch}. Move focus to the right.
988 */
989 public static final int FOCUS_RIGHT = 0x00000042;
990
991 /**
992 * Use with {@link #focusSearch}. Move focus down.
993 */
994 public static final int FOCUS_DOWN = 0x00000082;
995
996 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -0800997 * Bits of {@link #getMeasuredWidthAndState()} and
998 * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
999 */
1000 public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1001
1002 /**
1003 * Bits of {@link #getMeasuredWidthAndState()} and
1004 * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1005 */
1006 public static final int MEASURED_STATE_MASK = 0xff000000;
1007
1008 /**
1009 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1010 * for functions that combine both width and height into a single int,
1011 * such as {@link #getMeasuredState()} and the childState argument of
1012 * {@link #resolveSizeAndState(int, int, int)}.
1013 */
1014 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1015
1016 /**
1017 * Bit of {@link #getMeasuredWidthAndState()} and
1018 * {@link #getMeasuredWidthAndState()} that indicates the measured size
1019 * is smaller that the space the view would like to have.
1020 */
1021 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1022
1023 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 * Base View state sets
1025 */
1026 // Singles
1027 /**
1028 * Indicates the view has no states set. States are used with
1029 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1030 * view depending on its state.
1031 *
1032 * @see android.graphics.drawable.Drawable
1033 * @see #getDrawableState()
1034 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001035 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 /**
1037 * Indicates the view is enabled. States are used with
1038 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1039 * view depending on its state.
1040 *
1041 * @see android.graphics.drawable.Drawable
1042 * @see #getDrawableState()
1043 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001044 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 /**
1046 * Indicates the view is focused. States are used with
1047 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1048 * view depending on its state.
1049 *
1050 * @see android.graphics.drawable.Drawable
1051 * @see #getDrawableState()
1052 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001053 protected static final int[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 /**
1055 * Indicates the view is selected. States are used with
1056 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1057 * view depending on its state.
1058 *
1059 * @see android.graphics.drawable.Drawable
1060 * @see #getDrawableState()
1061 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001062 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 /**
1064 * Indicates the view is pressed. States are used with
1065 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1066 * view depending on its state.
1067 *
1068 * @see android.graphics.drawable.Drawable
1069 * @see #getDrawableState()
1070 * @hide
1071 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001072 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 /**
1074 * Indicates the view's window has focus. States are used with
1075 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1076 * view depending on its state.
1077 *
1078 * @see android.graphics.drawable.Drawable
1079 * @see #getDrawableState()
1080 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001081 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 // Doubles
1083 /**
1084 * Indicates the view is enabled and has the focus.
1085 *
1086 * @see #ENABLED_STATE_SET
1087 * @see #FOCUSED_STATE_SET
1088 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001089 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 /**
1091 * Indicates the view is enabled and selected.
1092 *
1093 * @see #ENABLED_STATE_SET
1094 * @see #SELECTED_STATE_SET
1095 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001096 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 /**
1098 * Indicates the view is enabled and that its window has focus.
1099 *
1100 * @see #ENABLED_STATE_SET
1101 * @see #WINDOW_FOCUSED_STATE_SET
1102 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001103 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 /**
1105 * Indicates the view is focused and selected.
1106 *
1107 * @see #FOCUSED_STATE_SET
1108 * @see #SELECTED_STATE_SET
1109 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001110 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 /**
1112 * Indicates the view has the focus and that its window has the focus.
1113 *
1114 * @see #FOCUSED_STATE_SET
1115 * @see #WINDOW_FOCUSED_STATE_SET
1116 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001117 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 /**
1119 * Indicates the view is selected and that its window has the focus.
1120 *
1121 * @see #SELECTED_STATE_SET
1122 * @see #WINDOW_FOCUSED_STATE_SET
1123 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001124 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 // Triples
1126 /**
1127 * Indicates the view is enabled, focused and selected.
1128 *
1129 * @see #ENABLED_STATE_SET
1130 * @see #FOCUSED_STATE_SET
1131 * @see #SELECTED_STATE_SET
1132 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001133 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 /**
1135 * Indicates the view is enabled, focused and its window has the focus.
1136 *
1137 * @see #ENABLED_STATE_SET
1138 * @see #FOCUSED_STATE_SET
1139 * @see #WINDOW_FOCUSED_STATE_SET
1140 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001141 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 /**
1143 * Indicates the view is enabled, selected and its window has the focus.
1144 *
1145 * @see #ENABLED_STATE_SET
1146 * @see #SELECTED_STATE_SET
1147 * @see #WINDOW_FOCUSED_STATE_SET
1148 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001149 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 /**
1151 * Indicates the view is focused, selected and its window has the focus.
1152 *
1153 * @see #FOCUSED_STATE_SET
1154 * @see #SELECTED_STATE_SET
1155 * @see #WINDOW_FOCUSED_STATE_SET
1156 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001157 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 /**
1159 * Indicates the view is enabled, focused, selected and its window
1160 * has the focus.
1161 *
1162 * @see #ENABLED_STATE_SET
1163 * @see #FOCUSED_STATE_SET
1164 * @see #SELECTED_STATE_SET
1165 * @see #WINDOW_FOCUSED_STATE_SET
1166 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001167 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 /**
1169 * Indicates the view is pressed and its window has the focus.
1170 *
1171 * @see #PRESSED_STATE_SET
1172 * @see #WINDOW_FOCUSED_STATE_SET
1173 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001174 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 /**
1176 * Indicates the view is pressed and selected.
1177 *
1178 * @see #PRESSED_STATE_SET
1179 * @see #SELECTED_STATE_SET
1180 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001181 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 /**
1183 * Indicates the view is pressed, selected and its window has the focus.
1184 *
1185 * @see #PRESSED_STATE_SET
1186 * @see #SELECTED_STATE_SET
1187 * @see #WINDOW_FOCUSED_STATE_SET
1188 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001189 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 /**
1191 * Indicates the view is pressed and focused.
1192 *
1193 * @see #PRESSED_STATE_SET
1194 * @see #FOCUSED_STATE_SET
1195 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001196 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 /**
1198 * Indicates the view is pressed, focused and its window has the focus.
1199 *
1200 * @see #PRESSED_STATE_SET
1201 * @see #FOCUSED_STATE_SET
1202 * @see #WINDOW_FOCUSED_STATE_SET
1203 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001204 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 /**
1206 * Indicates the view is pressed, focused and selected.
1207 *
1208 * @see #PRESSED_STATE_SET
1209 * @see #SELECTED_STATE_SET
1210 * @see #FOCUSED_STATE_SET
1211 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001212 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 /**
1214 * Indicates the view is pressed, focused, selected and its window has the focus.
1215 *
1216 * @see #PRESSED_STATE_SET
1217 * @see #FOCUSED_STATE_SET
1218 * @see #SELECTED_STATE_SET
1219 * @see #WINDOW_FOCUSED_STATE_SET
1220 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001221 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 /**
1223 * Indicates the view is pressed and enabled.
1224 *
1225 * @see #PRESSED_STATE_SET
1226 * @see #ENABLED_STATE_SET
1227 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001228 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 /**
1230 * Indicates the view is pressed, enabled and its window has the focus.
1231 *
1232 * @see #PRESSED_STATE_SET
1233 * @see #ENABLED_STATE_SET
1234 * @see #WINDOW_FOCUSED_STATE_SET
1235 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001236 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 /**
1238 * Indicates the view is pressed, enabled and selected.
1239 *
1240 * @see #PRESSED_STATE_SET
1241 * @see #ENABLED_STATE_SET
1242 * @see #SELECTED_STATE_SET
1243 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001244 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 /**
1246 * Indicates the view is pressed, enabled, selected and its window has the
1247 * focus.
1248 *
1249 * @see #PRESSED_STATE_SET
1250 * @see #ENABLED_STATE_SET
1251 * @see #SELECTED_STATE_SET
1252 * @see #WINDOW_FOCUSED_STATE_SET
1253 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001254 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 /**
1256 * Indicates the view is pressed, enabled and focused.
1257 *
1258 * @see #PRESSED_STATE_SET
1259 * @see #ENABLED_STATE_SET
1260 * @see #FOCUSED_STATE_SET
1261 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001262 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 /**
1264 * Indicates the view is pressed, enabled, focused and its window has the
1265 * focus.
1266 *
1267 * @see #PRESSED_STATE_SET
1268 * @see #ENABLED_STATE_SET
1269 * @see #FOCUSED_STATE_SET
1270 * @see #WINDOW_FOCUSED_STATE_SET
1271 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001272 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 /**
1274 * Indicates the view is pressed, enabled, focused and selected.
1275 *
1276 * @see #PRESSED_STATE_SET
1277 * @see #ENABLED_STATE_SET
1278 * @see #SELECTED_STATE_SET
1279 * @see #FOCUSED_STATE_SET
1280 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001281 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 /**
1283 * Indicates the view is pressed, enabled, focused, selected and its window
1284 * has the focus.
1285 *
1286 * @see #PRESSED_STATE_SET
1287 * @see #ENABLED_STATE_SET
1288 * @see #SELECTED_STATE_SET
1289 * @see #FOCUSED_STATE_SET
1290 * @see #WINDOW_FOCUSED_STATE_SET
1291 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001292 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293
1294 /**
1295 * The order here is very important to {@link #getDrawableState()}
1296 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001297 private static final int[][] VIEW_STATE_SETS;
1298
Romain Guyb051e892010-09-28 19:09:36 -07001299 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1300 static final int VIEW_STATE_SELECTED = 1 << 1;
1301 static final int VIEW_STATE_FOCUSED = 1 << 2;
1302 static final int VIEW_STATE_ENABLED = 1 << 3;
1303 static final int VIEW_STATE_PRESSED = 1 << 4;
1304 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001305 static final int VIEW_STATE_ACCELERATED = 1 << 6;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001306
1307 static final int[] VIEW_STATE_IDS = new int[] {
1308 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1309 R.attr.state_selected, VIEW_STATE_SELECTED,
1310 R.attr.state_focused, VIEW_STATE_FOCUSED,
1311 R.attr.state_enabled, VIEW_STATE_ENABLED,
1312 R.attr.state_pressed, VIEW_STATE_PRESSED,
1313 R.attr.state_activated, VIEW_STATE_ACTIVATED,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001314 R.attr.state_accelerated, VIEW_STATE_ACCELERATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 };
1316
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001317 static {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001318 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1319 throw new IllegalStateException(
1320 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1321 }
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001322 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001323 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001324 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001325 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001326 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001327 orderedIds[i * 2] = viewState;
1328 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001329 }
1330 }
1331 }
Romain Guyb051e892010-09-28 19:09:36 -07001332 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1333 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1334 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001335 int numBits = Integer.bitCount(i);
1336 int[] set = new int[numBits];
1337 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001338 for (int j = 0; j < orderedIds.length; j += 2) {
1339 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001340 set[pos++] = orderedIds[j];
1341 }
1342 }
1343 VIEW_STATE_SETS[i] = set;
1344 }
1345
1346 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1347 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1348 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1349 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1350 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1351 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1352 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1353 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1354 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1355 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1356 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1357 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1358 | VIEW_STATE_FOCUSED];
1359 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1360 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1361 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1362 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1363 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1364 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1365 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1366 | VIEW_STATE_ENABLED];
1367 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1368 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1369 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1370 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1371 | VIEW_STATE_ENABLED];
1372 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1373 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1374 | VIEW_STATE_ENABLED];
1375 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1376 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1377 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1378
1379 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1380 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1381 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1382 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1383 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1384 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1385 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1386 | VIEW_STATE_PRESSED];
1387 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1388 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1389 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1390 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1391 | VIEW_STATE_PRESSED];
1392 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1393 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1394 | VIEW_STATE_PRESSED];
1395 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1396 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1397 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1398 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1399 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1400 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1401 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1402 | VIEW_STATE_PRESSED];
1403 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1404 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1405 | VIEW_STATE_PRESSED];
1406 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1407 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1408 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1409 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1410 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1411 | VIEW_STATE_PRESSED];
1412 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1413 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1414 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1415 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1416 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1417 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1418 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1420 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1421 | VIEW_STATE_PRESSED];
1422 }
1423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 /**
1425 * Used by views that contain lists of items. This state indicates that
1426 * the view is showing the last item.
1427 * @hide
1428 */
1429 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1430 /**
1431 * Used by views that contain lists of items. This state indicates that
1432 * the view is showing the first item.
1433 * @hide
1434 */
1435 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1436 /**
1437 * Used by views that contain lists of items. This state indicates that
1438 * the view is showing the middle item.
1439 * @hide
1440 */
1441 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1442 /**
1443 * Used by views that contain lists of items. This state indicates that
1444 * the view is showing only one item.
1445 * @hide
1446 */
1447 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1448 /**
1449 * Used by views that contain lists of items. This state indicates that
1450 * the view is pressed and showing the last item.
1451 * @hide
1452 */
1453 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1454 /**
1455 * Used by views that contain lists of items. This state indicates that
1456 * the view is pressed and showing the first item.
1457 * @hide
1458 */
1459 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1460 /**
1461 * Used by views that contain lists of items. This state indicates that
1462 * the view is pressed and showing the middle item.
1463 * @hide
1464 */
1465 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1466 /**
1467 * Used by views that contain lists of items. This state indicates that
1468 * the view is pressed and showing only one item.
1469 * @hide
1470 */
1471 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1472
1473 /**
1474 * Temporary Rect currently for use in setBackground(). This will probably
1475 * be extended in the future to hold our own class with more than just
1476 * a Rect. :)
1477 */
1478 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001479
1480 /**
1481 * Map used to store views' tags.
1482 */
1483 private static WeakHashMap<View, SparseArray<Object>> sTags;
1484
1485 /**
1486 * Lock used to access sTags.
1487 */
1488 private static final Object sTagsLock = new Object();
1489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 /**
1491 * The animation currently associated with this view.
1492 * @hide
1493 */
1494 protected Animation mCurrentAnimation = null;
1495
1496 /**
1497 * Width as measured during measure pass.
1498 * {@hide}
1499 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001500 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001501 /*package*/ int mMeasuredWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502
1503 /**
1504 * Height as measured during measure pass.
1505 * {@hide}
1506 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001507 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001508 /*package*/ int mMeasuredHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509
1510 /**
1511 * The view's identifier.
1512 * {@hide}
1513 *
1514 * @see #setId(int)
1515 * @see #getId()
1516 */
1517 @ViewDebug.ExportedProperty(resolveId = true)
1518 int mID = NO_ID;
1519
1520 /**
1521 * The view's tag.
1522 * {@hide}
1523 *
1524 * @see #setTag(Object)
1525 * @see #getTag()
1526 */
1527 protected Object mTag;
1528
1529 // for mPrivateFlags:
1530 /** {@hide} */
1531 static final int WANTS_FOCUS = 0x00000001;
1532 /** {@hide} */
1533 static final int FOCUSED = 0x00000002;
1534 /** {@hide} */
1535 static final int SELECTED = 0x00000004;
1536 /** {@hide} */
1537 static final int IS_ROOT_NAMESPACE = 0x00000008;
1538 /** {@hide} */
1539 static final int HAS_BOUNDS = 0x00000010;
1540 /** {@hide} */
1541 static final int DRAWN = 0x00000020;
1542 /**
1543 * When this flag is set, this view is running an animation on behalf of its
1544 * children and should therefore not cancel invalidate requests, even if they
1545 * lie outside of this view's bounds.
1546 *
1547 * {@hide}
1548 */
1549 static final int DRAW_ANIMATION = 0x00000040;
1550 /** {@hide} */
1551 static final int SKIP_DRAW = 0x00000080;
1552 /** {@hide} */
1553 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1554 /** {@hide} */
1555 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1556 /** {@hide} */
1557 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1558 /** {@hide} */
1559 static final int MEASURED_DIMENSION_SET = 0x00000800;
1560 /** {@hide} */
1561 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001562 /** {@hide} */
1563 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564
1565 private static final int PRESSED = 0x00004000;
1566
1567 /** {@hide} */
1568 static final int DRAWING_CACHE_VALID = 0x00008000;
1569 /**
1570 * Flag used to indicate that this view should be drawn once more (and only once
1571 * more) after its animation has completed.
1572 * {@hide}
1573 */
1574 static final int ANIMATION_STARTED = 0x00010000;
1575
1576 private static final int SAVE_STATE_CALLED = 0x00020000;
1577
1578 /**
1579 * Indicates that the View returned true when onSetAlpha() was called and that
1580 * the alpha must be restored.
1581 * {@hide}
1582 */
1583 static final int ALPHA_SET = 0x00040000;
1584
1585 /**
1586 * Set by {@link #setScrollContainer(boolean)}.
1587 */
1588 static final int SCROLL_CONTAINER = 0x00080000;
1589
1590 /**
1591 * Set by {@link #setScrollContainer(boolean)}.
1592 */
1593 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1594
1595 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001596 * View flag indicating whether this view was invalidated (fully or partially.)
1597 *
1598 * @hide
1599 */
1600 static final int DIRTY = 0x00200000;
1601
1602 /**
1603 * View flag indicating whether this view was invalidated by an opaque
1604 * invalidate request.
1605 *
1606 * @hide
1607 */
1608 static final int DIRTY_OPAQUE = 0x00400000;
1609
1610 /**
1611 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1612 *
1613 * @hide
1614 */
1615 static final int DIRTY_MASK = 0x00600000;
1616
1617 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001618 * Indicates whether the background is opaque.
1619 *
1620 * @hide
1621 */
1622 static final int OPAQUE_BACKGROUND = 0x00800000;
1623
1624 /**
1625 * Indicates whether the scrollbars are opaque.
1626 *
1627 * @hide
1628 */
1629 static final int OPAQUE_SCROLLBARS = 0x01000000;
1630
1631 /**
1632 * Indicates whether the view is opaque.
1633 *
1634 * @hide
1635 */
1636 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001637
1638 /**
1639 * Indicates a prepressed state;
1640 * the short time between ACTION_DOWN and recognizing
1641 * a 'real' press. Prepressed is used to recognize quick taps
1642 * even when they are shorter than ViewConfiguration.getTapTimeout().
1643 *
1644 * @hide
1645 */
1646 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001647
1648 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001649 * Indicates whether the view is temporarily detached.
1650 *
1651 * @hide
1652 */
1653 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001654
1655 /**
1656 * Indicates that we should awaken scroll bars once attached
1657 *
1658 * @hide
1659 */
1660 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001661
1662 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001663 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1664 * for transform operations
1665 *
1666 * @hide
1667 */
Adam Powellf37df072010-09-17 16:22:49 -07001668 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001669
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001670 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001671 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001672
Chet Haasefd2b0022010-08-06 13:08:56 -07001673 /**
Adam Powell637d3372010-08-25 14:37:03 -07001674 * Always allow a user to over-scroll this view, provided it is a
1675 * view that can scroll.
1676 *
1677 * @see #getOverScrollMode()
1678 * @see #setOverScrollMode(int)
1679 */
1680 public static final int OVER_SCROLL_ALWAYS = 0;
1681
1682 /**
1683 * Allow a user to over-scroll this view only if the content is large
1684 * enough to meaningfully scroll, provided it is a view that can scroll.
1685 *
1686 * @see #getOverScrollMode()
1687 * @see #setOverScrollMode(int)
1688 */
1689 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1690
1691 /**
1692 * Never allow a user to over-scroll this view.
1693 *
1694 * @see #getOverScrollMode()
1695 * @see #setOverScrollMode(int)
1696 */
1697 public static final int OVER_SCROLL_NEVER = 2;
1698
1699 /**
1700 * Controls the over-scroll mode for this view.
1701 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1702 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1703 * and {@link #OVER_SCROLL_NEVER}.
1704 */
1705 private int mOverScrollMode;
1706
1707 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 * The parent this view is attached to.
1709 * {@hide}
1710 *
1711 * @see #getParent()
1712 */
1713 protected ViewParent mParent;
1714
1715 /**
1716 * {@hide}
1717 */
1718 AttachInfo mAttachInfo;
1719
1720 /**
1721 * {@hide}
1722 */
Romain Guy809a7f62009-05-14 15:44:42 -07001723 @ViewDebug.ExportedProperty(flagMapping = {
1724 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1725 name = "FORCE_LAYOUT"),
1726 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1727 name = "LAYOUT_REQUIRED"),
1728 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001729 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001730 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1731 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1732 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1733 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1734 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 int mPrivateFlags;
1736
1737 /**
1738 * Count of how many windows this view has been attached to.
1739 */
1740 int mWindowAttachCount;
1741
1742 /**
1743 * The layout parameters associated with this view and used by the parent
1744 * {@link android.view.ViewGroup} to determine how this view should be
1745 * laid out.
1746 * {@hide}
1747 */
1748 protected ViewGroup.LayoutParams mLayoutParams;
1749
1750 /**
1751 * The view flags hold various views states.
1752 * {@hide}
1753 */
1754 @ViewDebug.ExportedProperty
1755 int mViewFlags;
1756
1757 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001758 * The transform matrix for the View. This transform is calculated internally
1759 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1760 * is used by default. Do *not* use this variable directly; instead call
1761 * getMatrix(), which will automatically recalculate the matrix if necessary
1762 * to get the correct matrix based on the latest rotation and scale properties.
1763 */
1764 private final Matrix mMatrix = new Matrix();
1765
1766 /**
1767 * The transform matrix for the View. This transform is calculated internally
1768 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1769 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001770 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001771 * to get the correct matrix based on the latest rotation and scale properties.
1772 */
1773 private Matrix mInverseMatrix;
1774
1775 /**
1776 * An internal variable that tracks whether we need to recalculate the
1777 * transform matrix, based on whether the rotation or scaleX/Y properties
1778 * have changed since the matrix was last calculated.
1779 */
1780 private boolean mMatrixDirty = false;
1781
1782 /**
1783 * An internal variable that tracks whether we need to recalculate the
1784 * transform matrix, based on whether the rotation or scaleX/Y properties
1785 * have changed since the matrix was last calculated.
1786 */
1787 private boolean mInverseMatrixDirty = true;
1788
1789 /**
1790 * A variable that tracks whether we need to recalculate the
1791 * transform matrix, based on whether the rotation or scaleX/Y properties
1792 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001793 * is only valid after a call to updateMatrix() or to a function that
1794 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001795 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001796 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001797
1798 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001799 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1800 */
1801 private Camera mCamera = null;
1802
1803 /**
1804 * This matrix is used when computing the matrix for 3D rotations.
1805 */
1806 private Matrix matrix3D = null;
1807
1808 /**
1809 * These prev values are used to recalculate a centered pivot point when necessary. The
1810 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1811 * set), so thes values are only used then as well.
1812 */
1813 private int mPrevWidth = -1;
1814 private int mPrevHeight = -1;
1815
1816 /**
1817 * Convenience value to check for float values that are close enough to zero to be considered
1818 * zero.
1819 */
Romain Guy2542d192010-08-18 11:47:12 -07001820 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001821
1822 /**
1823 * The degrees rotation around the vertical axis through the pivot point.
1824 */
1825 @ViewDebug.ExportedProperty
1826 private float mRotationY = 0f;
1827
1828 /**
1829 * The degrees rotation around the horizontal axis through the pivot point.
1830 */
1831 @ViewDebug.ExportedProperty
1832 private float mRotationX = 0f;
1833
1834 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001835 * The degrees rotation around the pivot point.
1836 */
1837 @ViewDebug.ExportedProperty
1838 private float mRotation = 0f;
1839
1840 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001841 * The amount of translation of the object away from its left property (post-layout).
1842 */
1843 @ViewDebug.ExportedProperty
1844 private float mTranslationX = 0f;
1845
1846 /**
1847 * The amount of translation of the object away from its top property (post-layout).
1848 */
1849 @ViewDebug.ExportedProperty
1850 private float mTranslationY = 0f;
1851
1852 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001853 * The amount of scale in the x direction around the pivot point. A
1854 * value of 1 means no scaling is applied.
1855 */
1856 @ViewDebug.ExportedProperty
1857 private float mScaleX = 1f;
1858
1859 /**
1860 * The amount of scale in the y direction around the pivot point. A
1861 * value of 1 means no scaling is applied.
1862 */
1863 @ViewDebug.ExportedProperty
1864 private float mScaleY = 1f;
1865
1866 /**
1867 * The amount of scale in the x direction around the pivot point. A
1868 * value of 1 means no scaling is applied.
1869 */
1870 @ViewDebug.ExportedProperty
1871 private float mPivotX = 0f;
1872
1873 /**
1874 * The amount of scale in the y direction around the pivot point. A
1875 * value of 1 means no scaling is applied.
1876 */
1877 @ViewDebug.ExportedProperty
1878 private float mPivotY = 0f;
1879
1880 /**
1881 * The opacity of the View. This is a value from 0 to 1, where 0 means
1882 * completely transparent and 1 means completely opaque.
1883 */
1884 @ViewDebug.ExportedProperty
1885 private float mAlpha = 1f;
1886
1887 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 * The distance in pixels from the left edge of this view's parent
1889 * to the left edge of this view.
1890 * {@hide}
1891 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001892 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 protected int mLeft;
1894 /**
1895 * The distance in pixels from the left edge of this view's parent
1896 * to the right edge of this view.
1897 * {@hide}
1898 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001899 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 protected int mRight;
1901 /**
1902 * The distance in pixels from the top edge of this view's parent
1903 * to the top edge of this view.
1904 * {@hide}
1905 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001906 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 protected int mTop;
1908 /**
1909 * The distance in pixels from the top edge of this view's parent
1910 * to the bottom edge of this view.
1911 * {@hide}
1912 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001913 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 protected int mBottom;
1915
1916 /**
1917 * The offset, in pixels, by which the content of this view is scrolled
1918 * horizontally.
1919 * {@hide}
1920 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001921 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001922 protected int mScrollX;
1923 /**
1924 * The offset, in pixels, by which the content of this view is scrolled
1925 * vertically.
1926 * {@hide}
1927 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001928 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 protected int mScrollY;
1930
1931 /**
1932 * The left padding in pixels, that is the distance in pixels between the
1933 * left edge of this view and the left edge of its content.
1934 * {@hide}
1935 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001936 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 protected int mPaddingLeft;
1938 /**
1939 * The right padding in pixels, that is the distance in pixels between the
1940 * right edge of this view and the right edge of its content.
1941 * {@hide}
1942 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001943 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 protected int mPaddingRight;
1945 /**
1946 * The top padding in pixels, that is the distance in pixels between the
1947 * top edge of this view and the top edge of its content.
1948 * {@hide}
1949 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001950 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 protected int mPaddingTop;
1952 /**
1953 * The bottom padding in pixels, that is the distance in pixels between the
1954 * bottom edge of this view and the bottom edge of its content.
1955 * {@hide}
1956 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001957 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 protected int mPaddingBottom;
1959
1960 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001961 * Briefly describes the view and is primarily used for accessibility support.
1962 */
1963 private CharSequence mContentDescription;
1964
1965 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 * Cache the paddingRight set by the user to append to the scrollbar's size.
1967 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001968 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 int mUserPaddingRight;
1970
1971 /**
1972 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1973 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001974 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 int mUserPaddingBottom;
1976
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001977 /**
Adam Powell20232d02010-12-08 21:08:53 -08001978 * Cache the paddingLeft set by the user to append to the scrollbar's size.
1979 */
1980 @ViewDebug.ExportedProperty(category = "padding")
1981 int mUserPaddingLeft;
1982
1983 /**
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001984 * @hide
1985 */
1986 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1987 /**
1988 * @hide
1989 */
1990 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991
1992 private Resources mResources = null;
1993
1994 private Drawable mBGDrawable;
1995
1996 private int mBackgroundResource;
1997 private boolean mBackgroundSizeChanged;
1998
1999 /**
2000 * Listener used to dispatch focus change events.
2001 * This field should be made private, so it is hidden from the SDK.
2002 * {@hide}
2003 */
2004 protected OnFocusChangeListener mOnFocusChangeListener;
2005
2006 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002007 * Listeners for layout change events.
2008 */
2009 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2010
2011 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 * Listener used to dispatch click events.
2013 * This field should be made private, so it is hidden from the SDK.
2014 * {@hide}
2015 */
2016 protected OnClickListener mOnClickListener;
2017
2018 /**
2019 * Listener used to dispatch long click events.
2020 * This field should be made private, so it is hidden from the SDK.
2021 * {@hide}
2022 */
2023 protected OnLongClickListener mOnLongClickListener;
2024
2025 /**
2026 * Listener used to build the context menu.
2027 * This field should be made private, so it is hidden from the SDK.
2028 * {@hide}
2029 */
2030 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2031
2032 private OnKeyListener mOnKeyListener;
2033
2034 private OnTouchListener mOnTouchListener;
2035
Chris Tate32affef2010-10-18 15:29:21 -07002036 private OnDragListener mOnDragListener;
2037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 /**
2039 * The application environment this view lives in.
2040 * This field should be made private, so it is hidden from the SDK.
2041 * {@hide}
2042 */
2043 protected Context mContext;
2044
2045 private ScrollabilityCache mScrollCache;
2046
2047 private int[] mDrawableState = null;
2048
Romain Guy02890fd2010-08-06 17:58:44 -07002049 private Bitmap mDrawingCache;
2050 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07002051 private DisplayList mDisplayList;
Romain Guy6c319ca2011-01-11 14:29:25 -08002052 private HardwareLayer mHardwareLayer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053
2054 /**
2055 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2056 * the user may specify which view to go to next.
2057 */
2058 private int mNextFocusLeftId = View.NO_ID;
2059
2060 /**
2061 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2062 * the user may specify which view to go to next.
2063 */
2064 private int mNextFocusRightId = View.NO_ID;
2065
2066 /**
2067 * When this view has focus and the next focus is {@link #FOCUS_UP},
2068 * the user may specify which view to go to next.
2069 */
2070 private int mNextFocusUpId = View.NO_ID;
2071
2072 /**
2073 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2074 * the user may specify which view to go to next.
2075 */
2076 private int mNextFocusDownId = View.NO_ID;
2077
Jeff Brown4e6319b2010-12-13 10:36:51 -08002078 /**
2079 * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2080 * the user may specify which view to go to next.
2081 */
2082 int mNextFocusForwardId = View.NO_ID;
2083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08002085 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08002086 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08002087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 private UnsetPressedState mUnsetPressedState;
2089
2090 /**
2091 * Whether the long press's action has been invoked. The tap's action is invoked on the
2092 * up event while a long press is invoked as soon as the long press duration is reached, so
2093 * a long press could be performed before the tap is checked, in which case the tap's action
2094 * should not be invoked.
2095 */
2096 private boolean mHasPerformedLongPress;
2097
2098 /**
2099 * The minimum height of the view. We'll try our best to have the height
2100 * of this view to at least this amount.
2101 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002102 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 private int mMinHeight;
2104
2105 /**
2106 * The minimum width of the view. We'll try our best to have the width
2107 * of this view to at least this amount.
2108 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002109 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 private int mMinWidth;
2111
2112 /**
2113 * The delegate to handle touch events that are physically in this view
2114 * but should be handled by another view.
2115 */
2116 private TouchDelegate mTouchDelegate = null;
2117
2118 /**
2119 * Solid color to use as a background when creating the drawing cache. Enables
2120 * the cache to use 16 bit bitmaps instead of 32 bit.
2121 */
2122 private int mDrawingCacheBackgroundColor = 0;
2123
2124 /**
2125 * Special tree observer used when mAttachInfo is null.
2126 */
2127 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08002128
2129 /**
2130 * Cache the touch slop from the context that created the view.
2131 */
2132 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002135 * Cache drag/drop state
2136 *
2137 */
2138 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002139
2140 /**
Christopher Tate02d2b3b2011-01-10 20:43:53 -08002141 * Flag indicating that a drag can cross window boundaries
2142 * @hide
2143 */
2144 public static final int DRAG_FLAG_GLOBAL = 1;
2145
2146 /**
Adam Powell20232d02010-12-08 21:08:53 -08002147 * Position of the vertical scroll bar.
2148 */
2149 private int mVerticalScrollbarPosition;
2150
2151 /**
2152 * Position the scroll bar at the default position as determined by the system.
2153 */
2154 public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2155
2156 /**
2157 * Position the scroll bar along the left edge.
2158 */
2159 public static final int SCROLLBAR_POSITION_LEFT = 1;
2160
2161 /**
2162 * Position the scroll bar along the right edge.
2163 */
2164 public static final int SCROLLBAR_POSITION_RIGHT = 2;
2165
2166 /**
Romain Guy171c5922011-01-06 10:04:23 -08002167 * Indicates that the view does not have a layer.
2168 *
2169 * @see #getLayerType()
2170 * @see #setLayerType(int, android.graphics.Paint)
2171 * @see #LAYER_TYPE_SOFTWARE
2172 * @see #LAYER_TYPE_HARDWARE
2173 */
2174 public static final int LAYER_TYPE_NONE = 0;
2175
2176 /**
2177 * <p>Indicates that the view has a software layer. A software layer is backed
2178 * by a bitmap and causes the view to be rendered using Android's software
2179 * rendering pipeline, even if hardware acceleration is enabled.</p>
2180 *
2181 * <p>Software layers have various usages:</p>
2182 * <p>When the application is not using hardware acceleration, a software layer
2183 * is useful to apply a specific color filter and/or blending mode and/or
2184 * translucency to a view and all its children.</p>
2185 * <p>When the application is using hardware acceleration, a software layer
2186 * is useful to render drawing primitives not supported by the hardware
2187 * accelerated pipeline. It can also be used to cache a complex view tree
2188 * into a texture and reduce the complexity of drawing operations. For instance,
2189 * when animating a complex view tree with a translation, a software layer can
2190 * be used to render the view tree only once.</p>
2191 * <p>Software layers should be avoided when the affected view tree updates
2192 * often. Every update will require to re-render the software layer, which can
2193 * potentially be slow (particularly when hardware acceleration is turned on
2194 * since the layer will have to be uploaded into a hardware texture after every
2195 * update.)</p>
2196 *
2197 * @see #getLayerType()
2198 * @see #setLayerType(int, android.graphics.Paint)
2199 * @see #LAYER_TYPE_NONE
2200 * @see #LAYER_TYPE_HARDWARE
2201 */
2202 public static final int LAYER_TYPE_SOFTWARE = 1;
2203
2204 /**
2205 * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2206 * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2207 * OpenGL hardware) and causes the view to be rendered using Android's hardware
2208 * rendering pipeline, but only if hardware acceleration is turned on for the
2209 * view hierarchy. When hardware acceleration is turned off, hardware layers
2210 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2211 *
2212 * <p>A hardware layer is useful to apply a specific color filter and/or
2213 * blending mode and/or translucency to a view and all its children.</p>
Romain Guy6c319ca2011-01-11 14:29:25 -08002214 * <p>A hardware layer can be used to cache a complex view tree into a
2215 * texture and reduce the complexity of drawing operations. For instance,
2216 * when animating a complex view tree with a translation, a hardware layer can
2217 * be used to render the view tree only once.</p>
Romain Guy171c5922011-01-06 10:04:23 -08002218 * <p>A hardware layer can also be used to increase the rendering quality when
2219 * rotation transformations are applied on a view. It can also be used to
2220 * prevent potential clipping issues when applying 3D transforms on a view.</p>
2221 *
2222 * @see #getLayerType()
2223 * @see #setLayerType(int, android.graphics.Paint)
2224 * @see #LAYER_TYPE_NONE
2225 * @see #LAYER_TYPE_SOFTWARE
2226 */
2227 public static final int LAYER_TYPE_HARDWARE = 2;
2228
Romain Guy3aaff3a2011-01-12 14:18:47 -08002229 @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2230 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2231 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2232 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2233 })
Romain Guy171c5922011-01-06 10:04:23 -08002234 int mLayerType = LAYER_TYPE_NONE;
2235 Paint mLayerPaint;
2236
2237 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 * Simple constructor to use when creating a view from code.
2239 *
2240 * @param context The Context the view is running in, through which it can
2241 * access the current theme, resources, etc.
2242 */
2243 public View(Context context) {
2244 mContext = context;
2245 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002246 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002247 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
Adam Powell637d3372010-08-25 14:37:03 -07002248 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 }
2250
2251 /**
2252 * Constructor that is called when inflating a view from XML. This is called
2253 * when a view is being constructed from an XML file, supplying attributes
2254 * that were specified in the XML file. This version uses a default style of
2255 * 0, so the only attribute values applied are those in the Context's Theme
2256 * and the given AttributeSet.
2257 *
2258 * <p>
2259 * The method onFinishInflate() will be called after all children have been
2260 * added.
2261 *
2262 * @param context The Context the view is running in, through which it can
2263 * access the current theme, resources, etc.
2264 * @param attrs The attributes of the XML tag that is inflating the view.
2265 * @see #View(Context, AttributeSet, int)
2266 */
2267 public View(Context context, AttributeSet attrs) {
2268 this(context, attrs, 0);
2269 }
2270
2271 /**
2272 * Perform inflation from XML and apply a class-specific base style. This
2273 * constructor of View allows subclasses to use their own base style when
2274 * they are inflating. For example, a Button class's constructor would call
2275 * this version of the super class constructor and supply
2276 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2277 * the theme's button style to modify all of the base view attributes (in
2278 * particular its background) as well as the Button class's attributes.
2279 *
2280 * @param context The Context the view is running in, through which it can
2281 * access the current theme, resources, etc.
2282 * @param attrs The attributes of the XML tag that is inflating the view.
2283 * @param defStyle The default style to apply to this view. If 0, no style
2284 * will be applied (beyond what is included in the theme). This may
2285 * either be an attribute resource, whose value will be retrieved
2286 * from the current theme, or an explicit style resource.
2287 * @see #View(Context, AttributeSet)
2288 */
2289 public View(Context context, AttributeSet attrs, int defStyle) {
2290 this(context);
2291
2292 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2293 defStyle, 0);
2294
2295 Drawable background = null;
2296
2297 int leftPadding = -1;
2298 int topPadding = -1;
2299 int rightPadding = -1;
2300 int bottomPadding = -1;
2301
2302 int padding = -1;
2303
2304 int viewFlagValues = 0;
2305 int viewFlagMasks = 0;
2306
2307 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 int x = 0;
2310 int y = 0;
2311
Chet Haase73066682010-11-29 15:55:32 -08002312 float tx = 0;
2313 float ty = 0;
2314 float rotation = 0;
2315 float rotationX = 0;
2316 float rotationY = 0;
2317 float sx = 1f;
2318 float sy = 1f;
2319 boolean transformSet = false;
2320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2322
Adam Powell637d3372010-08-25 14:37:03 -07002323 int overScrollMode = mOverScrollMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 final int N = a.getIndexCount();
2325 for (int i = 0; i < N; i++) {
2326 int attr = a.getIndex(i);
2327 switch (attr) {
2328 case com.android.internal.R.styleable.View_background:
2329 background = a.getDrawable(attr);
2330 break;
2331 case com.android.internal.R.styleable.View_padding:
2332 padding = a.getDimensionPixelSize(attr, -1);
2333 break;
2334 case com.android.internal.R.styleable.View_paddingLeft:
2335 leftPadding = a.getDimensionPixelSize(attr, -1);
2336 break;
2337 case com.android.internal.R.styleable.View_paddingTop:
2338 topPadding = a.getDimensionPixelSize(attr, -1);
2339 break;
2340 case com.android.internal.R.styleable.View_paddingRight:
2341 rightPadding = a.getDimensionPixelSize(attr, -1);
2342 break;
2343 case com.android.internal.R.styleable.View_paddingBottom:
2344 bottomPadding = a.getDimensionPixelSize(attr, -1);
2345 break;
2346 case com.android.internal.R.styleable.View_scrollX:
2347 x = a.getDimensionPixelOffset(attr, 0);
2348 break;
2349 case com.android.internal.R.styleable.View_scrollY:
2350 y = a.getDimensionPixelOffset(attr, 0);
2351 break;
Chet Haase73066682010-11-29 15:55:32 -08002352 case com.android.internal.R.styleable.View_alpha:
2353 setAlpha(a.getFloat(attr, 1f));
2354 break;
2355 case com.android.internal.R.styleable.View_transformPivotX:
2356 setPivotX(a.getDimensionPixelOffset(attr, 0));
2357 break;
2358 case com.android.internal.R.styleable.View_transformPivotY:
2359 setPivotY(a.getDimensionPixelOffset(attr, 0));
2360 break;
2361 case com.android.internal.R.styleable.View_translationX:
2362 tx = a.getDimensionPixelOffset(attr, 0);
2363 transformSet = true;
2364 break;
2365 case com.android.internal.R.styleable.View_translationY:
2366 ty = a.getDimensionPixelOffset(attr, 0);
2367 transformSet = true;
2368 break;
2369 case com.android.internal.R.styleable.View_rotation:
2370 rotation = a.getFloat(attr, 0);
2371 transformSet = true;
2372 break;
2373 case com.android.internal.R.styleable.View_rotationX:
2374 rotationX = a.getFloat(attr, 0);
2375 transformSet = true;
2376 break;
2377 case com.android.internal.R.styleable.View_rotationY:
2378 rotationY = a.getFloat(attr, 0);
2379 transformSet = true;
2380 break;
2381 case com.android.internal.R.styleable.View_scaleX:
2382 sx = a.getFloat(attr, 1f);
2383 transformSet = true;
2384 break;
2385 case com.android.internal.R.styleable.View_scaleY:
2386 sy = a.getFloat(attr, 1f);
2387 transformSet = true;
2388 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 case com.android.internal.R.styleable.View_id:
2390 mID = a.getResourceId(attr, NO_ID);
2391 break;
2392 case com.android.internal.R.styleable.View_tag:
2393 mTag = a.getText(attr);
2394 break;
2395 case com.android.internal.R.styleable.View_fitsSystemWindows:
2396 if (a.getBoolean(attr, false)) {
2397 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2398 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2399 }
2400 break;
2401 case com.android.internal.R.styleable.View_focusable:
2402 if (a.getBoolean(attr, false)) {
2403 viewFlagValues |= FOCUSABLE;
2404 viewFlagMasks |= FOCUSABLE_MASK;
2405 }
2406 break;
2407 case com.android.internal.R.styleable.View_focusableInTouchMode:
2408 if (a.getBoolean(attr, false)) {
2409 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2410 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2411 }
2412 break;
2413 case com.android.internal.R.styleable.View_clickable:
2414 if (a.getBoolean(attr, false)) {
2415 viewFlagValues |= CLICKABLE;
2416 viewFlagMasks |= CLICKABLE;
2417 }
2418 break;
2419 case com.android.internal.R.styleable.View_longClickable:
2420 if (a.getBoolean(attr, false)) {
2421 viewFlagValues |= LONG_CLICKABLE;
2422 viewFlagMasks |= LONG_CLICKABLE;
2423 }
2424 break;
2425 case com.android.internal.R.styleable.View_saveEnabled:
2426 if (!a.getBoolean(attr, true)) {
2427 viewFlagValues |= SAVE_DISABLED;
2428 viewFlagMasks |= SAVE_DISABLED_MASK;
2429 }
2430 break;
2431 case com.android.internal.R.styleable.View_duplicateParentState:
2432 if (a.getBoolean(attr, false)) {
2433 viewFlagValues |= DUPLICATE_PARENT_STATE;
2434 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2435 }
2436 break;
2437 case com.android.internal.R.styleable.View_visibility:
2438 final int visibility = a.getInt(attr, 0);
2439 if (visibility != 0) {
2440 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2441 viewFlagMasks |= VISIBILITY_MASK;
2442 }
2443 break;
2444 case com.android.internal.R.styleable.View_drawingCacheQuality:
2445 final int cacheQuality = a.getInt(attr, 0);
2446 if (cacheQuality != 0) {
2447 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2448 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2449 }
2450 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002451 case com.android.internal.R.styleable.View_contentDescription:
2452 mContentDescription = a.getString(attr);
2453 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2455 if (!a.getBoolean(attr, true)) {
2456 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2457 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2458 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002459 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2461 if (!a.getBoolean(attr, true)) {
2462 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2463 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2464 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002465 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 case R.styleable.View_scrollbars:
2467 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2468 if (scrollbars != SCROLLBARS_NONE) {
2469 viewFlagValues |= scrollbars;
2470 viewFlagMasks |= SCROLLBARS_MASK;
2471 initializeScrollbars(a);
2472 }
2473 break;
2474 case R.styleable.View_fadingEdge:
2475 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2476 if (fadingEdge != FADING_EDGE_NONE) {
2477 viewFlagValues |= fadingEdge;
2478 viewFlagMasks |= FADING_EDGE_MASK;
2479 initializeFadingEdge(a);
2480 }
2481 break;
2482 case R.styleable.View_scrollbarStyle:
2483 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2484 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2485 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2486 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2487 }
2488 break;
2489 case R.styleable.View_isScrollContainer:
2490 setScrollContainer = true;
2491 if (a.getBoolean(attr, false)) {
2492 setScrollContainer(true);
2493 }
2494 break;
2495 case com.android.internal.R.styleable.View_keepScreenOn:
2496 if (a.getBoolean(attr, false)) {
2497 viewFlagValues |= KEEP_SCREEN_ON;
2498 viewFlagMasks |= KEEP_SCREEN_ON;
2499 }
2500 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002501 case R.styleable.View_filterTouchesWhenObscured:
2502 if (a.getBoolean(attr, false)) {
2503 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2504 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2505 }
2506 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 case R.styleable.View_nextFocusLeft:
2508 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2509 break;
2510 case R.styleable.View_nextFocusRight:
2511 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2512 break;
2513 case R.styleable.View_nextFocusUp:
2514 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2515 break;
2516 case R.styleable.View_nextFocusDown:
2517 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2518 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002519 case R.styleable.View_nextFocusForward:
2520 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2521 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 case R.styleable.View_minWidth:
2523 mMinWidth = a.getDimensionPixelSize(attr, 0);
2524 break;
2525 case R.styleable.View_minHeight:
2526 mMinHeight = a.getDimensionPixelSize(attr, 0);
2527 break;
Romain Guy9a817362009-05-01 10:57:14 -07002528 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002529 if (context.isRestricted()) {
2530 throw new IllegalStateException("The android:onClick attribute cannot "
2531 + "be used within a restricted context");
2532 }
2533
Romain Guy9a817362009-05-01 10:57:14 -07002534 final String handlerName = a.getString(attr);
2535 if (handlerName != null) {
2536 setOnClickListener(new OnClickListener() {
2537 private Method mHandler;
2538
2539 public void onClick(View v) {
2540 if (mHandler == null) {
2541 try {
2542 mHandler = getContext().getClass().getMethod(handlerName,
2543 View.class);
2544 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002545 int id = getId();
2546 String idText = id == NO_ID ? "" : " with id '"
2547 + getContext().getResources().getResourceEntryName(
2548 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002549 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002550 handlerName + "(View) in the activity "
2551 + getContext().getClass() + " for onClick handler"
2552 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002553 }
2554 }
2555
2556 try {
2557 mHandler.invoke(getContext(), View.this);
2558 } catch (IllegalAccessException e) {
2559 throw new IllegalStateException("Could not execute non "
2560 + "public method of the activity", e);
2561 } catch (InvocationTargetException e) {
2562 throw new IllegalStateException("Could not execute "
2563 + "method of the activity", e);
2564 }
2565 }
2566 });
2567 }
2568 break;
Adam Powell637d3372010-08-25 14:37:03 -07002569 case R.styleable.View_overScrollMode:
2570 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2571 break;
Adam Powell20232d02010-12-08 21:08:53 -08002572 case R.styleable.View_verticalScrollbarPosition:
2573 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2574 break;
Romain Guy171c5922011-01-06 10:04:23 -08002575 case R.styleable.View_layerType:
2576 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
2577 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 }
2579 }
2580
Adam Powell637d3372010-08-25 14:37:03 -07002581 setOverScrollMode(overScrollMode);
2582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 if (background != null) {
2584 setBackgroundDrawable(background);
2585 }
2586
2587 if (padding >= 0) {
2588 leftPadding = padding;
2589 topPadding = padding;
2590 rightPadding = padding;
2591 bottomPadding = padding;
2592 }
2593
2594 // If the user specified the padding (either with android:padding or
2595 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2596 // use the default padding or the padding from the background drawable
2597 // (stored at this point in mPadding*)
2598 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2599 topPadding >= 0 ? topPadding : mPaddingTop,
2600 rightPadding >= 0 ? rightPadding : mPaddingRight,
2601 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2602
2603 if (viewFlagMasks != 0) {
2604 setFlags(viewFlagValues, viewFlagMasks);
2605 }
2606
2607 // Needs to be called after mViewFlags is set
2608 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2609 recomputePadding();
2610 }
2611
2612 if (x != 0 || y != 0) {
2613 scrollTo(x, y);
2614 }
2615
Chet Haase73066682010-11-29 15:55:32 -08002616 if (transformSet) {
2617 setTranslationX(tx);
2618 setTranslationY(ty);
2619 setRotation(rotation);
2620 setRotationX(rotationX);
2621 setRotationY(rotationY);
2622 setScaleX(sx);
2623 setScaleY(sy);
2624 }
2625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2627 setScrollContainer(true);
2628 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002629
2630 computeOpaqueFlags();
2631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 a.recycle();
2633 }
2634
2635 /**
2636 * Non-public constructor for use in testing
2637 */
2638 View() {
2639 }
2640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 /**
2642 * <p>
2643 * Initializes the fading edges from a given set of styled attributes. This
2644 * method should be called by subclasses that need fading edges and when an
2645 * instance of these subclasses is created programmatically rather than
2646 * being inflated from XML. This method is automatically called when the XML
2647 * is inflated.
2648 * </p>
2649 *
2650 * @param a the styled attributes set to initialize the fading edges from
2651 */
2652 protected void initializeFadingEdge(TypedArray a) {
2653 initScrollCache();
2654
2655 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2656 R.styleable.View_fadingEdgeLength,
2657 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2658 }
2659
2660 /**
2661 * Returns the size of the vertical faded edges used to indicate that more
2662 * content in this view is visible.
2663 *
2664 * @return The size in pixels of the vertical faded edge or 0 if vertical
2665 * faded edges are not enabled for this view.
2666 * @attr ref android.R.styleable#View_fadingEdgeLength
2667 */
2668 public int getVerticalFadingEdgeLength() {
2669 if (isVerticalFadingEdgeEnabled()) {
2670 ScrollabilityCache cache = mScrollCache;
2671 if (cache != null) {
2672 return cache.fadingEdgeLength;
2673 }
2674 }
2675 return 0;
2676 }
2677
2678 /**
2679 * Set the size of the faded edge used to indicate that more content in this
2680 * view is available. Will not change whether the fading edge is enabled; use
2681 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2682 * to enable the fading edge for the vertical or horizontal fading edges.
2683 *
2684 * @param length The size in pixels of the faded edge used to indicate that more
2685 * content in this view is visible.
2686 */
2687 public void setFadingEdgeLength(int length) {
2688 initScrollCache();
2689 mScrollCache.fadingEdgeLength = length;
2690 }
2691
2692 /**
2693 * Returns the size of the horizontal faded edges used to indicate that more
2694 * content in this view is visible.
2695 *
2696 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2697 * faded edges are not enabled for this view.
2698 * @attr ref android.R.styleable#View_fadingEdgeLength
2699 */
2700 public int getHorizontalFadingEdgeLength() {
2701 if (isHorizontalFadingEdgeEnabled()) {
2702 ScrollabilityCache cache = mScrollCache;
2703 if (cache != null) {
2704 return cache.fadingEdgeLength;
2705 }
2706 }
2707 return 0;
2708 }
2709
2710 /**
2711 * Returns the width of the vertical scrollbar.
2712 *
2713 * @return The width in pixels of the vertical scrollbar or 0 if there
2714 * is no vertical scrollbar.
2715 */
2716 public int getVerticalScrollbarWidth() {
2717 ScrollabilityCache cache = mScrollCache;
2718 if (cache != null) {
2719 ScrollBarDrawable scrollBar = cache.scrollBar;
2720 if (scrollBar != null) {
2721 int size = scrollBar.getSize(true);
2722 if (size <= 0) {
2723 size = cache.scrollBarSize;
2724 }
2725 return size;
2726 }
2727 return 0;
2728 }
2729 return 0;
2730 }
2731
2732 /**
2733 * Returns the height of the horizontal scrollbar.
2734 *
2735 * @return The height in pixels of the horizontal scrollbar or 0 if
2736 * there is no horizontal scrollbar.
2737 */
2738 protected int getHorizontalScrollbarHeight() {
2739 ScrollabilityCache cache = mScrollCache;
2740 if (cache != null) {
2741 ScrollBarDrawable scrollBar = cache.scrollBar;
2742 if (scrollBar != null) {
2743 int size = scrollBar.getSize(false);
2744 if (size <= 0) {
2745 size = cache.scrollBarSize;
2746 }
2747 return size;
2748 }
2749 return 0;
2750 }
2751 return 0;
2752 }
2753
2754 /**
2755 * <p>
2756 * Initializes the scrollbars from a given set of styled attributes. This
2757 * method should be called by subclasses that need scrollbars and when an
2758 * instance of these subclasses is created programmatically rather than
2759 * being inflated from XML. This method is automatically called when the XML
2760 * is inflated.
2761 * </p>
2762 *
2763 * @param a the styled attributes set to initialize the scrollbars from
2764 */
2765 protected void initializeScrollbars(TypedArray a) {
2766 initScrollCache();
2767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002769
2770 if (scrollabilityCache.scrollBar == null) {
2771 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2772 }
2773
Romain Guy8bda2482010-03-02 11:42:11 -08002774 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775
Mike Cleronf116bf82009-09-27 19:14:12 -07002776 if (!fadeScrollbars) {
2777 scrollabilityCache.state = ScrollabilityCache.ON;
2778 }
2779 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2780
2781
2782 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2783 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2784 .getScrollBarFadeDuration());
2785 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2786 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2787 ViewConfiguration.getScrollDefaultDelay());
2788
2789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2791 com.android.internal.R.styleable.View_scrollbarSize,
2792 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2793
2794 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2795 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2796
2797 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2798 if (thumb != null) {
2799 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2800 }
2801
2802 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2803 false);
2804 if (alwaysDraw) {
2805 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2806 }
2807
2808 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2809 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2810
2811 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2812 if (thumb != null) {
2813 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2814 }
2815
2816 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2817 false);
2818 if (alwaysDraw) {
2819 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2820 }
2821
2822 // Re-apply user/background padding so that scrollbar(s) get added
2823 recomputePadding();
2824 }
2825
2826 /**
2827 * <p>
2828 * Initalizes the scrollability cache if necessary.
2829 * </p>
2830 */
2831 private void initScrollCache() {
2832 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002833 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 }
2835 }
2836
2837 /**
Adam Powell20232d02010-12-08 21:08:53 -08002838 * Set the position of the vertical scroll bar. Should be one of
2839 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
2840 * {@link #SCROLLBAR_POSITION_RIGHT}.
2841 *
2842 * @param position Where the vertical scroll bar should be positioned.
2843 */
2844 public void setVerticalScrollbarPosition(int position) {
2845 if (mVerticalScrollbarPosition != position) {
2846 mVerticalScrollbarPosition = position;
2847 computeOpaqueFlags();
2848 recomputePadding();
2849 }
2850 }
2851
2852 /**
2853 * @return The position where the vertical scroll bar will show, if applicable.
2854 * @see #setVerticalScrollbarPosition(int)
2855 */
2856 public int getVerticalScrollbarPosition() {
2857 return mVerticalScrollbarPosition;
2858 }
2859
2860 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 * Register a callback to be invoked when focus of this view changed.
2862 *
2863 * @param l The callback that will run.
2864 */
2865 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2866 mOnFocusChangeListener = l;
2867 }
2868
2869 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002870 * Add a listener that will be called when the bounds of the view change due to
2871 * layout processing.
2872 *
2873 * @param listener The listener that will be called when layout bounds change.
2874 */
2875 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2876 if (mOnLayoutChangeListeners == null) {
2877 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2878 }
2879 mOnLayoutChangeListeners.add(listener);
2880 }
2881
2882 /**
2883 * Remove a listener for layout changes.
2884 *
2885 * @param listener The listener for layout bounds change.
2886 */
2887 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2888 if (mOnLayoutChangeListeners == null) {
2889 return;
2890 }
2891 mOnLayoutChangeListeners.remove(listener);
2892 }
2893
2894 /**
2895 * Gets the current list of listeners for layout changes.
Chet Haase21cd1382010-09-01 17:42:29 -07002896 */
2897 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2898 return mOnLayoutChangeListeners;
2899 }
2900
2901 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 * Returns the focus-change callback registered for this view.
2903 *
2904 * @return The callback, or null if one is not registered.
2905 */
2906 public OnFocusChangeListener getOnFocusChangeListener() {
2907 return mOnFocusChangeListener;
2908 }
2909
2910 /**
2911 * Register a callback to be invoked when this view is clicked. If this view is not
2912 * clickable, it becomes clickable.
2913 *
2914 * @param l The callback that will run
2915 *
2916 * @see #setClickable(boolean)
2917 */
2918 public void setOnClickListener(OnClickListener l) {
2919 if (!isClickable()) {
2920 setClickable(true);
2921 }
2922 mOnClickListener = l;
2923 }
2924
2925 /**
2926 * Register a callback to be invoked when this view is clicked and held. If this view is not
2927 * long clickable, it becomes long clickable.
2928 *
2929 * @param l The callback that will run
2930 *
2931 * @see #setLongClickable(boolean)
2932 */
2933 public void setOnLongClickListener(OnLongClickListener l) {
2934 if (!isLongClickable()) {
2935 setLongClickable(true);
2936 }
2937 mOnLongClickListener = l;
2938 }
2939
2940 /**
2941 * Register a callback to be invoked when the context menu for this view is
2942 * being built. If this view is not long clickable, it becomes long clickable.
2943 *
2944 * @param l The callback that will run
2945 *
2946 */
2947 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2948 if (!isLongClickable()) {
2949 setLongClickable(true);
2950 }
2951 mOnCreateContextMenuListener = l;
2952 }
2953
2954 /**
2955 * Call this view's OnClickListener, if it is defined.
2956 *
2957 * @return True there was an assigned OnClickListener that was called, false
2958 * otherwise is returned.
2959 */
2960 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002961 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963 if (mOnClickListener != null) {
2964 playSoundEffect(SoundEffectConstants.CLICK);
2965 mOnClickListener.onClick(this);
2966 return true;
2967 }
2968
2969 return false;
2970 }
2971
2972 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002973 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2974 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002976 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 */
2978 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002979 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 boolean handled = false;
2982 if (mOnLongClickListener != null) {
2983 handled = mOnLongClickListener.onLongClick(View.this);
2984 }
2985 if (!handled) {
2986 handled = showContextMenu();
2987 }
2988 if (handled) {
2989 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2990 }
2991 return handled;
2992 }
2993
2994 /**
2995 * Bring up the context menu for this view.
2996 *
2997 * @return Whether a context menu was displayed.
2998 */
2999 public boolean showContextMenu() {
3000 return getParent().showContextMenuForChild(this);
3001 }
3002
3003 /**
Adam Powell6e346362010-07-23 10:18:23 -07003004 * Start an action mode.
3005 *
3006 * @param callback Callback that will control the lifecycle of the action mode
3007 * @return The new action mode if it is started, null otherwise
3008 *
3009 * @see ActionMode
3010 */
3011 public ActionMode startActionMode(ActionMode.Callback callback) {
3012 return getParent().startActionModeForChild(this, callback);
3013 }
3014
3015 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 * Register a callback to be invoked when a key is pressed in this view.
3017 * @param l the key listener to attach to this view
3018 */
3019 public void setOnKeyListener(OnKeyListener l) {
3020 mOnKeyListener = l;
3021 }
3022
3023 /**
3024 * Register a callback to be invoked when a touch event is sent to this view.
3025 * @param l the touch listener to attach to this view
3026 */
3027 public void setOnTouchListener(OnTouchListener l) {
3028 mOnTouchListener = l;
3029 }
3030
3031 /**
Chris Tate32affef2010-10-18 15:29:21 -07003032 * Register a callback to be invoked when a drag event is sent to this view.
3033 * @param l The drag listener to attach to this view
3034 */
3035 public void setOnDragListener(OnDragListener l) {
3036 mOnDragListener = l;
3037 }
3038
3039 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
3041 *
3042 * Note: this does not check whether this {@link View} should get focus, it just
3043 * gives it focus no matter what. It should only be called internally by framework
3044 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3045 *
3046 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
3047 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
3048 * focus moved when requestFocus() is called. It may not always
3049 * apply, in which case use the default View.FOCUS_DOWN.
3050 * @param previouslyFocusedRect The rectangle of the view that had focus
3051 * prior in this View's coordinate system.
3052 */
3053 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3054 if (DBG) {
3055 System.out.println(this + " requestFocus()");
3056 }
3057
3058 if ((mPrivateFlags & FOCUSED) == 0) {
3059 mPrivateFlags |= FOCUSED;
3060
3061 if (mParent != null) {
3062 mParent.requestChildFocus(this, this);
3063 }
3064
3065 onFocusChanged(true, direction, previouslyFocusedRect);
3066 refreshDrawableState();
3067 }
3068 }
3069
3070 /**
3071 * Request that a rectangle of this view be visible on the screen,
3072 * scrolling if necessary just enough.
3073 *
3074 * <p>A View should call this if it maintains some notion of which part
3075 * of its content is interesting. For example, a text editing view
3076 * should call this when its cursor moves.
3077 *
3078 * @param rectangle The rectangle.
3079 * @return Whether any parent scrolled.
3080 */
3081 public boolean requestRectangleOnScreen(Rect rectangle) {
3082 return requestRectangleOnScreen(rectangle, false);
3083 }
3084
3085 /**
3086 * Request that a rectangle of this view be visible on the screen,
3087 * scrolling if necessary just enough.
3088 *
3089 * <p>A View should call this if it maintains some notion of which part
3090 * of its content is interesting. For example, a text editing view
3091 * should call this when its cursor moves.
3092 *
3093 * <p>When <code>immediate</code> is set to true, scrolling will not be
3094 * animated.
3095 *
3096 * @param rectangle The rectangle.
3097 * @param immediate True to forbid animated scrolling, false otherwise
3098 * @return Whether any parent scrolled.
3099 */
3100 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3101 View child = this;
3102 ViewParent parent = mParent;
3103 boolean scrolled = false;
3104 while (parent != null) {
3105 scrolled |= parent.requestChildRectangleOnScreen(child,
3106 rectangle, immediate);
3107
3108 // offset rect so next call has the rectangle in the
3109 // coordinate system of its direct child.
3110 rectangle.offset(child.getLeft(), child.getTop());
3111 rectangle.offset(-child.getScrollX(), -child.getScrollY());
3112
3113 if (!(parent instanceof View)) {
3114 break;
3115 }
Romain Guy8506ab42009-06-11 17:35:47 -07003116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117 child = (View) parent;
3118 parent = child.getParent();
3119 }
3120 return scrolled;
3121 }
3122
3123 /**
3124 * Called when this view wants to give up focus. This will cause
3125 * {@link #onFocusChanged} to be called.
3126 */
3127 public void clearFocus() {
3128 if (DBG) {
3129 System.out.println(this + " clearFocus()");
3130 }
3131
3132 if ((mPrivateFlags & FOCUSED) != 0) {
3133 mPrivateFlags &= ~FOCUSED;
3134
3135 if (mParent != null) {
3136 mParent.clearChildFocus(this);
3137 }
3138
3139 onFocusChanged(false, 0, null);
3140 refreshDrawableState();
3141 }
3142 }
3143
3144 /**
3145 * Called to clear the focus of a view that is about to be removed.
3146 * Doesn't call clearChildFocus, which prevents this view from taking
3147 * focus again before it has been removed from the parent
3148 */
3149 void clearFocusForRemoval() {
3150 if ((mPrivateFlags & FOCUSED) != 0) {
3151 mPrivateFlags &= ~FOCUSED;
3152
3153 onFocusChanged(false, 0, null);
3154 refreshDrawableState();
3155 }
3156 }
3157
3158 /**
3159 * Called internally by the view system when a new view is getting focus.
3160 * This is what clears the old focus.
3161 */
3162 void unFocus() {
3163 if (DBG) {
3164 System.out.println(this + " unFocus()");
3165 }
3166
3167 if ((mPrivateFlags & FOCUSED) != 0) {
3168 mPrivateFlags &= ~FOCUSED;
3169
3170 onFocusChanged(false, 0, null);
3171 refreshDrawableState();
3172 }
3173 }
3174
3175 /**
3176 * Returns true if this view has focus iteself, or is the ancestor of the
3177 * view that has focus.
3178 *
3179 * @return True if this view has or contains focus, false otherwise.
3180 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003181 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 public boolean hasFocus() {
3183 return (mPrivateFlags & FOCUSED) != 0;
3184 }
3185
3186 /**
3187 * Returns true if this view is focusable or if it contains a reachable View
3188 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3189 * is a View whose parents do not block descendants focus.
3190 *
3191 * Only {@link #VISIBLE} views are considered focusable.
3192 *
3193 * @return True if the view is focusable or if the view contains a focusable
3194 * View, false otherwise.
3195 *
3196 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3197 */
3198 public boolean hasFocusable() {
3199 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3200 }
3201
3202 /**
3203 * Called by the view system when the focus state of this view changes.
3204 * When the focus change event is caused by directional navigation, direction
3205 * and previouslyFocusedRect provide insight into where the focus is coming from.
3206 * When overriding, be sure to call up through to the super class so that
3207 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07003208 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 * @param gainFocus True if the View has focus; false otherwise.
3210 * @param direction The direction focus has moved when requestFocus()
3211 * is called to give this view focus. Values are
Jeff Brown4e6319b2010-12-13 10:36:51 -08003212 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3213 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3214 * It may not always apply, in which case use the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 * @param previouslyFocusedRect The rectangle, in this view's coordinate
3216 * system, of the previously focused view. If applicable, this will be
3217 * passed in as finer grained information about where the focus is coming
3218 * from (in addition to direction). Will be <code>null</code> otherwise.
3219 */
3220 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003221 if (gainFocus) {
3222 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3223 }
3224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 InputMethodManager imm = InputMethodManager.peekInstance();
3226 if (!gainFocus) {
3227 if (isPressed()) {
3228 setPressed(false);
3229 }
3230 if (imm != null && mAttachInfo != null
3231 && mAttachInfo.mHasWindowFocus) {
3232 imm.focusOut(this);
3233 }
Romain Guya2431d02009-04-30 16:30:00 -07003234 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235 } else if (imm != null && mAttachInfo != null
3236 && mAttachInfo.mHasWindowFocus) {
3237 imm.focusIn(this);
3238 }
Romain Guy8506ab42009-06-11 17:35:47 -07003239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 invalidate();
3241 if (mOnFocusChangeListener != null) {
3242 mOnFocusChangeListener.onFocusChange(this, gainFocus);
3243 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003244
3245 if (mAttachInfo != null) {
3246 mAttachInfo.mKeyDispatchState.reset(this);
3247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003248 }
3249
3250 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07003251 * {@inheritDoc}
3252 */
3253 public void sendAccessibilityEvent(int eventType) {
3254 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3255 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3256 }
3257 }
3258
3259 /**
3260 * {@inheritDoc}
3261 */
3262 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
Svetoslav Ganov9cd1eca2011-01-13 14:24:02 -08003263 if (!isShown()) {
3264 return;
3265 }
svetoslavganov75986cf2009-05-14 22:28:01 -07003266 event.setClassName(getClass().getName());
3267 event.setPackageName(getContext().getPackageName());
3268 event.setEnabled(isEnabled());
3269 event.setContentDescription(mContentDescription);
3270
3271 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3272 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3273 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3274 event.setItemCount(focusablesTempList.size());
3275 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3276 focusablesTempList.clear();
3277 }
3278
3279 dispatchPopulateAccessibilityEvent(event);
3280
3281 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
3282 }
3283
3284 /**
3285 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3286 * to be populated.
3287 *
3288 * @param event The event.
3289 *
3290 * @return True if the event population was completed.
3291 */
3292 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3293 return false;
3294 }
3295
3296 /**
3297 * Gets the {@link View} description. It briefly describes the view and is
3298 * primarily used for accessibility support. Set this property to enable
3299 * better accessibility support for your application. This is especially
3300 * true for views that do not have textual representation (For example,
3301 * ImageButton).
3302 *
3303 * @return The content descriptiopn.
3304 *
3305 * @attr ref android.R.styleable#View_contentDescription
3306 */
3307 public CharSequence getContentDescription() {
3308 return mContentDescription;
3309 }
3310
3311 /**
3312 * Sets the {@link View} description. It briefly describes the view and is
3313 * primarily used for accessibility support. Set this property to enable
3314 * better accessibility support for your application. This is especially
3315 * true for views that do not have textual representation (For example,
3316 * ImageButton).
3317 *
3318 * @param contentDescription The content description.
3319 *
3320 * @attr ref android.R.styleable#View_contentDescription
3321 */
3322 public void setContentDescription(CharSequence contentDescription) {
3323 mContentDescription = contentDescription;
3324 }
3325
3326 /**
Romain Guya2431d02009-04-30 16:30:00 -07003327 * Invoked whenever this view loses focus, either by losing window focus or by losing
3328 * focus within its window. This method can be used to clear any state tied to the
3329 * focus. For instance, if a button is held pressed with the trackball and the window
3330 * loses focus, this method can be used to cancel the press.
3331 *
3332 * Subclasses of View overriding this method should always call super.onFocusLost().
3333 *
3334 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003335 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003336 *
3337 * @hide pending API council approval
3338 */
3339 protected void onFocusLost() {
3340 resetPressedState();
3341 }
3342
3343 private void resetPressedState() {
3344 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3345 return;
3346 }
3347
3348 if (isPressed()) {
3349 setPressed(false);
3350
3351 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003352 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003353 }
3354 }
3355 }
3356
3357 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 * Returns true if this view has focus
3359 *
3360 * @return True if this view has focus, false otherwise.
3361 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003362 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 public boolean isFocused() {
3364 return (mPrivateFlags & FOCUSED) != 0;
3365 }
3366
3367 /**
3368 * Find the view in the hierarchy rooted at this view that currently has
3369 * focus.
3370 *
3371 * @return The view that currently has focus, or null if no focused view can
3372 * be found.
3373 */
3374 public View findFocus() {
3375 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3376 }
3377
3378 /**
3379 * Change whether this view is one of the set of scrollable containers in
3380 * its window. This will be used to determine whether the window can
3381 * resize or must pan when a soft input area is open -- scrollable
3382 * containers allow the window to use resize mode since the container
3383 * will appropriately shrink.
3384 */
3385 public void setScrollContainer(boolean isScrollContainer) {
3386 if (isScrollContainer) {
3387 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3388 mAttachInfo.mScrollContainers.add(this);
3389 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3390 }
3391 mPrivateFlags |= SCROLL_CONTAINER;
3392 } else {
3393 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3394 mAttachInfo.mScrollContainers.remove(this);
3395 }
3396 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3397 }
3398 }
3399
3400 /**
3401 * Returns the quality of the drawing cache.
3402 *
3403 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3404 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3405 *
3406 * @see #setDrawingCacheQuality(int)
3407 * @see #setDrawingCacheEnabled(boolean)
3408 * @see #isDrawingCacheEnabled()
3409 *
3410 * @attr ref android.R.styleable#View_drawingCacheQuality
3411 */
3412 public int getDrawingCacheQuality() {
3413 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3414 }
3415
3416 /**
3417 * Set the drawing cache quality of this view. This value is used only when the
3418 * drawing cache is enabled
3419 *
3420 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3421 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3422 *
3423 * @see #getDrawingCacheQuality()
3424 * @see #setDrawingCacheEnabled(boolean)
3425 * @see #isDrawingCacheEnabled()
3426 *
3427 * @attr ref android.R.styleable#View_drawingCacheQuality
3428 */
3429 public void setDrawingCacheQuality(int quality) {
3430 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3431 }
3432
3433 /**
3434 * Returns whether the screen should remain on, corresponding to the current
3435 * value of {@link #KEEP_SCREEN_ON}.
3436 *
3437 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3438 *
3439 * @see #setKeepScreenOn(boolean)
3440 *
3441 * @attr ref android.R.styleable#View_keepScreenOn
3442 */
3443 public boolean getKeepScreenOn() {
3444 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3445 }
3446
3447 /**
3448 * Controls whether the screen should remain on, modifying the
3449 * value of {@link #KEEP_SCREEN_ON}.
3450 *
3451 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3452 *
3453 * @see #getKeepScreenOn()
3454 *
3455 * @attr ref android.R.styleable#View_keepScreenOn
3456 */
3457 public void setKeepScreenOn(boolean keepScreenOn) {
3458 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3459 }
3460
3461 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003462 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3463 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003464 *
3465 * @attr ref android.R.styleable#View_nextFocusLeft
3466 */
3467 public int getNextFocusLeftId() {
3468 return mNextFocusLeftId;
3469 }
3470
3471 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003472 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3473 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
3474 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 *
3476 * @attr ref android.R.styleable#View_nextFocusLeft
3477 */
3478 public void setNextFocusLeftId(int nextFocusLeftId) {
3479 mNextFocusLeftId = nextFocusLeftId;
3480 }
3481
3482 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003483 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3484 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 *
3486 * @attr ref android.R.styleable#View_nextFocusRight
3487 */
3488 public int getNextFocusRightId() {
3489 return mNextFocusRightId;
3490 }
3491
3492 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003493 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3494 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
3495 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 *
3497 * @attr ref android.R.styleable#View_nextFocusRight
3498 */
3499 public void setNextFocusRightId(int nextFocusRightId) {
3500 mNextFocusRightId = nextFocusRightId;
3501 }
3502
3503 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003504 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3505 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 *
3507 * @attr ref android.R.styleable#View_nextFocusUp
3508 */
3509 public int getNextFocusUpId() {
3510 return mNextFocusUpId;
3511 }
3512
3513 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003514 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3515 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
3516 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 *
3518 * @attr ref android.R.styleable#View_nextFocusUp
3519 */
3520 public void setNextFocusUpId(int nextFocusUpId) {
3521 mNextFocusUpId = nextFocusUpId;
3522 }
3523
3524 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003525 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3526 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 *
3528 * @attr ref android.R.styleable#View_nextFocusDown
3529 */
3530 public int getNextFocusDownId() {
3531 return mNextFocusDownId;
3532 }
3533
3534 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003535 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3536 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
3537 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 *
3539 * @attr ref android.R.styleable#View_nextFocusDown
3540 */
3541 public void setNextFocusDownId(int nextFocusDownId) {
3542 mNextFocusDownId = nextFocusDownId;
3543 }
3544
3545 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003546 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3547 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3548 *
3549 * @attr ref android.R.styleable#View_nextFocusForward
3550 */
3551 public int getNextFocusForwardId() {
3552 return mNextFocusForwardId;
3553 }
3554
3555 /**
3556 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3557 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
3558 * decide automatically.
3559 *
3560 * @attr ref android.R.styleable#View_nextFocusForward
3561 */
3562 public void setNextFocusForwardId(int nextFocusForwardId) {
3563 mNextFocusForwardId = nextFocusForwardId;
3564 }
3565
3566 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 * Returns the visibility of this view and all of its ancestors
3568 *
3569 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3570 */
3571 public boolean isShown() {
3572 View current = this;
3573 //noinspection ConstantConditions
3574 do {
3575 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3576 return false;
3577 }
3578 ViewParent parent = current.mParent;
3579 if (parent == null) {
3580 return false; // We are not attached to the view root
3581 }
3582 if (!(parent instanceof View)) {
3583 return true;
3584 }
3585 current = (View) parent;
3586 } while (current != null);
3587
3588 return false;
3589 }
3590
3591 /**
3592 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3593 * is set
3594 *
3595 * @param insets Insets for system windows
3596 *
3597 * @return True if this view applied the insets, false otherwise
3598 */
3599 protected boolean fitSystemWindows(Rect insets) {
3600 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3601 mPaddingLeft = insets.left;
3602 mPaddingTop = insets.top;
3603 mPaddingRight = insets.right;
3604 mPaddingBottom = insets.bottom;
3605 requestLayout();
3606 return true;
3607 }
3608 return false;
3609 }
3610
3611 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003612 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3613 * @return True if window has FITS_SYSTEM_WINDOWS set
3614 *
3615 * @hide
3616 */
3617 public boolean isFitsSystemWindowsFlagSet() {
3618 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3619 }
3620
3621 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 * Returns the visibility status for this view.
3623 *
3624 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3625 * @attr ref android.R.styleable#View_visibility
3626 */
3627 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003628 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3629 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3630 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 })
3632 public int getVisibility() {
3633 return mViewFlags & VISIBILITY_MASK;
3634 }
3635
3636 /**
3637 * Set the enabled state of this view.
3638 *
3639 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3640 * @attr ref android.R.styleable#View_visibility
3641 */
3642 @RemotableViewMethod
3643 public void setVisibility(int visibility) {
3644 setFlags(visibility, VISIBILITY_MASK);
3645 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3646 }
3647
3648 /**
3649 * Returns the enabled status for this view. The interpretation of the
3650 * enabled state varies by subclass.
3651 *
3652 * @return True if this view is enabled, false otherwise.
3653 */
3654 @ViewDebug.ExportedProperty
3655 public boolean isEnabled() {
3656 return (mViewFlags & ENABLED_MASK) == ENABLED;
3657 }
3658
3659 /**
3660 * Set the enabled state of this view. The interpretation of the enabled
3661 * state varies by subclass.
3662 *
3663 * @param enabled True if this view is enabled, false otherwise.
3664 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003665 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003667 if (enabled == isEnabled()) return;
3668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3670
3671 /*
3672 * The View most likely has to change its appearance, so refresh
3673 * the drawable state.
3674 */
3675 refreshDrawableState();
3676
3677 // Invalidate too, since the default behavior for views is to be
3678 // be drawn at 50% alpha rather than to change the drawable.
3679 invalidate();
3680 }
3681
3682 /**
3683 * Set whether this view can receive the focus.
3684 *
3685 * Setting this to false will also ensure that this view is not focusable
3686 * in touch mode.
3687 *
3688 * @param focusable If true, this view can receive the focus.
3689 *
3690 * @see #setFocusableInTouchMode(boolean)
3691 * @attr ref android.R.styleable#View_focusable
3692 */
3693 public void setFocusable(boolean focusable) {
3694 if (!focusable) {
3695 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3696 }
3697 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3698 }
3699
3700 /**
3701 * Set whether this view can receive focus while in touch mode.
3702 *
3703 * Setting this to true will also ensure that this view is focusable.
3704 *
3705 * @param focusableInTouchMode If true, this view can receive the focus while
3706 * in touch mode.
3707 *
3708 * @see #setFocusable(boolean)
3709 * @attr ref android.R.styleable#View_focusableInTouchMode
3710 */
3711 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3712 // Focusable in touch mode should always be set before the focusable flag
3713 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3714 // which, in touch mode, will not successfully request focus on this view
3715 // because the focusable in touch mode flag is not set
3716 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3717 if (focusableInTouchMode) {
3718 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3719 }
3720 }
3721
3722 /**
3723 * Set whether this view should have sound effects enabled for events such as
3724 * clicking and touching.
3725 *
3726 * <p>You may wish to disable sound effects for a view if you already play sounds,
3727 * for instance, a dial key that plays dtmf tones.
3728 *
3729 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3730 * @see #isSoundEffectsEnabled()
3731 * @see #playSoundEffect(int)
3732 * @attr ref android.R.styleable#View_soundEffectsEnabled
3733 */
3734 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3735 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3736 }
3737
3738 /**
3739 * @return whether this view should have sound effects enabled for events such as
3740 * clicking and touching.
3741 *
3742 * @see #setSoundEffectsEnabled(boolean)
3743 * @see #playSoundEffect(int)
3744 * @attr ref android.R.styleable#View_soundEffectsEnabled
3745 */
3746 @ViewDebug.ExportedProperty
3747 public boolean isSoundEffectsEnabled() {
3748 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3749 }
3750
3751 /**
3752 * Set whether this view should have haptic feedback for events such as
3753 * long presses.
3754 *
3755 * <p>You may wish to disable haptic feedback if your view already controls
3756 * its own haptic feedback.
3757 *
3758 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3759 * @see #isHapticFeedbackEnabled()
3760 * @see #performHapticFeedback(int)
3761 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3762 */
3763 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3764 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3765 }
3766
3767 /**
3768 * @return whether this view should have haptic feedback enabled for events
3769 * long presses.
3770 *
3771 * @see #setHapticFeedbackEnabled(boolean)
3772 * @see #performHapticFeedback(int)
3773 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3774 */
3775 @ViewDebug.ExportedProperty
3776 public boolean isHapticFeedbackEnabled() {
3777 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3778 }
3779
3780 /**
3781 * If this view doesn't do any drawing on its own, set this flag to
3782 * allow further optimizations. By default, this flag is not set on
3783 * View, but could be set on some View subclasses such as ViewGroup.
3784 *
3785 * Typically, if you override {@link #onDraw} you should clear this flag.
3786 *
3787 * @param willNotDraw whether or not this View draw on its own
3788 */
3789 public void setWillNotDraw(boolean willNotDraw) {
3790 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3791 }
3792
3793 /**
3794 * Returns whether or not this View draws on its own.
3795 *
3796 * @return true if this view has nothing to draw, false otherwise
3797 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003798 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 public boolean willNotDraw() {
3800 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3801 }
3802
3803 /**
3804 * When a View's drawing cache is enabled, drawing is redirected to an
3805 * offscreen bitmap. Some views, like an ImageView, must be able to
3806 * bypass this mechanism if they already draw a single bitmap, to avoid
3807 * unnecessary usage of the memory.
3808 *
3809 * @param willNotCacheDrawing true if this view does not cache its
3810 * drawing, false otherwise
3811 */
3812 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3813 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3814 }
3815
3816 /**
3817 * Returns whether or not this View can cache its drawing or not.
3818 *
3819 * @return true if this view does not cache its drawing, false otherwise
3820 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003821 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822 public boolean willNotCacheDrawing() {
3823 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3824 }
3825
3826 /**
3827 * Indicates whether this view reacts to click events or not.
3828 *
3829 * @return true if the view is clickable, false otherwise
3830 *
3831 * @see #setClickable(boolean)
3832 * @attr ref android.R.styleable#View_clickable
3833 */
3834 @ViewDebug.ExportedProperty
3835 public boolean isClickable() {
3836 return (mViewFlags & CLICKABLE) == CLICKABLE;
3837 }
3838
3839 /**
3840 * Enables or disables click events for this view. When a view
3841 * is clickable it will change its state to "pressed" on every click.
3842 * Subclasses should set the view clickable to visually react to
3843 * user's clicks.
3844 *
3845 * @param clickable true to make the view clickable, false otherwise
3846 *
3847 * @see #isClickable()
3848 * @attr ref android.R.styleable#View_clickable
3849 */
3850 public void setClickable(boolean clickable) {
3851 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3852 }
3853
3854 /**
3855 * Indicates whether this view reacts to long click events or not.
3856 *
3857 * @return true if the view is long clickable, false otherwise
3858 *
3859 * @see #setLongClickable(boolean)
3860 * @attr ref android.R.styleable#View_longClickable
3861 */
3862 public boolean isLongClickable() {
3863 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3864 }
3865
3866 /**
3867 * Enables or disables long click events for this view. When a view is long
3868 * clickable it reacts to the user holding down the button for a longer
3869 * duration than a tap. This event can either launch the listener or a
3870 * context menu.
3871 *
3872 * @param longClickable true to make the view long clickable, false otherwise
3873 * @see #isLongClickable()
3874 * @attr ref android.R.styleable#View_longClickable
3875 */
3876 public void setLongClickable(boolean longClickable) {
3877 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3878 }
3879
3880 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003881 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 *
3883 * @see #isClickable()
3884 * @see #setClickable(boolean)
3885 *
3886 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3887 * the View's internal state from a previously set "pressed" state.
3888 */
3889 public void setPressed(boolean pressed) {
3890 if (pressed) {
3891 mPrivateFlags |= PRESSED;
3892 } else {
3893 mPrivateFlags &= ~PRESSED;
3894 }
3895 refreshDrawableState();
3896 dispatchSetPressed(pressed);
3897 }
3898
3899 /**
3900 * Dispatch setPressed to all of this View's children.
3901 *
3902 * @see #setPressed(boolean)
3903 *
3904 * @param pressed The new pressed state
3905 */
3906 protected void dispatchSetPressed(boolean pressed) {
3907 }
3908
3909 /**
3910 * Indicates whether the view is currently in pressed state. Unless
3911 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3912 * the pressed state.
3913 *
3914 * @see #setPressed
3915 * @see #isClickable()
3916 * @see #setClickable(boolean)
3917 *
3918 * @return true if the view is currently pressed, false otherwise
3919 */
3920 public boolean isPressed() {
3921 return (mPrivateFlags & PRESSED) == PRESSED;
3922 }
3923
3924 /**
3925 * Indicates whether this view will save its state (that is,
3926 * whether its {@link #onSaveInstanceState} method will be called).
3927 *
3928 * @return Returns true if the view state saving is enabled, else false.
3929 *
3930 * @see #setSaveEnabled(boolean)
3931 * @attr ref android.R.styleable#View_saveEnabled
3932 */
3933 public boolean isSaveEnabled() {
3934 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3935 }
3936
3937 /**
3938 * Controls whether the saving of this view's state is
3939 * enabled (that is, whether its {@link #onSaveInstanceState} method
3940 * will be called). Note that even if freezing is enabled, the
3941 * view still must have an id assigned to it (via {@link #setId setId()})
3942 * for its state to be saved. This flag can only disable the
3943 * saving of this view; any child views may still have their state saved.
3944 *
3945 * @param enabled Set to false to <em>disable</em> state saving, or true
3946 * (the default) to allow it.
3947 *
3948 * @see #isSaveEnabled()
3949 * @see #setId(int)
3950 * @see #onSaveInstanceState()
3951 * @attr ref android.R.styleable#View_saveEnabled
3952 */
3953 public void setSaveEnabled(boolean enabled) {
3954 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3955 }
3956
Jeff Brown85a31762010-09-01 17:01:00 -07003957 /**
3958 * Gets whether the framework should discard touches when the view's
3959 * window is obscured by another visible window.
3960 * Refer to the {@link View} security documentation for more details.
3961 *
3962 * @return True if touch filtering is enabled.
3963 *
3964 * @see #setFilterTouchesWhenObscured(boolean)
3965 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3966 */
3967 @ViewDebug.ExportedProperty
3968 public boolean getFilterTouchesWhenObscured() {
3969 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3970 }
3971
3972 /**
3973 * Sets whether the framework should discard touches when the view's
3974 * window is obscured by another visible window.
3975 * Refer to the {@link View} security documentation for more details.
3976 *
3977 * @param enabled True if touch filtering should be enabled.
3978 *
3979 * @see #getFilterTouchesWhenObscured
3980 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3981 */
3982 public void setFilterTouchesWhenObscured(boolean enabled) {
3983 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3984 FILTER_TOUCHES_WHEN_OBSCURED);
3985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986
3987 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003988 * Indicates whether the entire hierarchy under this view will save its
3989 * state when a state saving traversal occurs from its parent. The default
3990 * is true; if false, these views will not be saved unless
3991 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3992 *
3993 * @return Returns true if the view state saving from parent is enabled, else false.
3994 *
3995 * @see #setSaveFromParentEnabled(boolean)
3996 */
3997 public boolean isSaveFromParentEnabled() {
3998 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3999 }
4000
4001 /**
4002 * Controls whether the entire hierarchy under this view will save its
4003 * state when a state saving traversal occurs from its parent. The default
4004 * is true; if false, these views will not be saved unless
4005 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4006 *
4007 * @param enabled Set to false to <em>disable</em> state saving, or true
4008 * (the default) to allow it.
4009 *
4010 * @see #isSaveFromParentEnabled()
4011 * @see #setId(int)
4012 * @see #onSaveInstanceState()
4013 */
4014 public void setSaveFromParentEnabled(boolean enabled) {
4015 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4016 }
4017
4018
4019 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 * Returns whether this View is able to take focus.
4021 *
4022 * @return True if this view can take focus, or false otherwise.
4023 * @attr ref android.R.styleable#View_focusable
4024 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004025 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 public final boolean isFocusable() {
4027 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4028 }
4029
4030 /**
4031 * When a view is focusable, it may not want to take focus when in touch mode.
4032 * For example, a button would like focus when the user is navigating via a D-pad
4033 * so that the user can click on it, but once the user starts touching the screen,
4034 * the button shouldn't take focus
4035 * @return Whether the view is focusable in touch mode.
4036 * @attr ref android.R.styleable#View_focusableInTouchMode
4037 */
4038 @ViewDebug.ExportedProperty
4039 public final boolean isFocusableInTouchMode() {
4040 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
4041 }
4042
4043 /**
4044 * Find the nearest view in the specified direction that can take focus.
4045 * This does not actually give focus to that view.
4046 *
4047 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4048 *
4049 * @return The nearest focusable in the specified direction, or null if none
4050 * can be found.
4051 */
4052 public View focusSearch(int direction) {
4053 if (mParent != null) {
4054 return mParent.focusSearch(this, direction);
4055 } else {
4056 return null;
4057 }
4058 }
4059
4060 /**
4061 * This method is the last chance for the focused view and its ancestors to
4062 * respond to an arrow key. This is called when the focused view did not
4063 * consume the key internally, nor could the view system find a new view in
4064 * the requested direction to give focus to.
4065 *
4066 * @param focused The currently focused view.
4067 * @param direction The direction focus wants to move. One of FOCUS_UP,
4068 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
4069 * @return True if the this view consumed this unhandled move.
4070 */
4071 public boolean dispatchUnhandledMove(View focused, int direction) {
4072 return false;
4073 }
4074
4075 /**
4076 * If a user manually specified the next view id for a particular direction,
Jeff Brown4e6319b2010-12-13 10:36:51 -08004077 * use the root to look up the view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 * @param root The root view of the hierarchy containing this view.
Jeff Brown4e6319b2010-12-13 10:36:51 -08004079 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
4080 * or FOCUS_BACKWARD.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004081 * @return The user specified next view, or null if there is none.
4082 */
4083 View findUserSetNextFocus(View root, int direction) {
4084 switch (direction) {
4085 case FOCUS_LEFT:
4086 if (mNextFocusLeftId == View.NO_ID) return null;
4087 return findViewShouldExist(root, mNextFocusLeftId);
4088 case FOCUS_RIGHT:
4089 if (mNextFocusRightId == View.NO_ID) return null;
4090 return findViewShouldExist(root, mNextFocusRightId);
4091 case FOCUS_UP:
4092 if (mNextFocusUpId == View.NO_ID) return null;
4093 return findViewShouldExist(root, mNextFocusUpId);
4094 case FOCUS_DOWN:
4095 if (mNextFocusDownId == View.NO_ID) return null;
4096 return findViewShouldExist(root, mNextFocusDownId);
Jeff Brown4e6319b2010-12-13 10:36:51 -08004097 case FOCUS_FORWARD:
4098 if (mNextFocusForwardId == View.NO_ID) return null;
4099 return findViewShouldExist(root, mNextFocusForwardId);
4100 case FOCUS_BACKWARD: {
4101 final int id = mID;
4102 return root.findViewByPredicate(new Predicate<View>() {
4103 @Override
4104 public boolean apply(View t) {
4105 return t.mNextFocusForwardId == id;
4106 }
4107 });
4108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 }
4110 return null;
4111 }
4112
4113 private static View findViewShouldExist(View root, int childViewId) {
4114 View result = root.findViewById(childViewId);
4115 if (result == null) {
4116 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4117 + "by user for id " + childViewId);
4118 }
4119 return result;
4120 }
4121
4122 /**
4123 * Find and return all focusable views that are descendants of this view,
4124 * possibly including this view if it is focusable itself.
4125 *
4126 * @param direction The direction of the focus
4127 * @return A list of focusable views
4128 */
4129 public ArrayList<View> getFocusables(int direction) {
4130 ArrayList<View> result = new ArrayList<View>(24);
4131 addFocusables(result, direction);
4132 return result;
4133 }
4134
4135 /**
4136 * Add any focusable views that are descendants of this view (possibly
4137 * including this view if it is focusable itself) to views. If we are in touch mode,
4138 * only add views that are also focusable in touch mode.
4139 *
4140 * @param views Focusable views found so far
4141 * @param direction The direction of the focus
4142 */
4143 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07004144 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146
svetoslavganov75986cf2009-05-14 22:28:01 -07004147 /**
4148 * Adds any focusable views that are descendants of this view (possibly
4149 * including this view if it is focusable itself) to views. This method
4150 * adds all focusable views regardless if we are in touch mode or
4151 * only views focusable in touch mode if we are in touch mode depending on
4152 * the focusable mode paramater.
4153 *
4154 * @param views Focusable views found so far or null if all we are interested is
4155 * the number of focusables.
4156 * @param direction The direction of the focus.
4157 * @param focusableMode The type of focusables to be added.
4158 *
4159 * @see #FOCUSABLES_ALL
4160 * @see #FOCUSABLES_TOUCH_MODE
4161 */
4162 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4163 if (!isFocusable()) {
4164 return;
4165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166
svetoslavganov75986cf2009-05-14 22:28:01 -07004167 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4168 isInTouchMode() && !isFocusableInTouchMode()) {
4169 return;
4170 }
4171
4172 if (views != null) {
4173 views.add(this);
4174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 }
4176
4177 /**
4178 * Find and return all touchable views that are descendants of this view,
4179 * possibly including this view if it is touchable itself.
4180 *
4181 * @return A list of touchable views
4182 */
4183 public ArrayList<View> getTouchables() {
4184 ArrayList<View> result = new ArrayList<View>();
4185 addTouchables(result);
4186 return result;
4187 }
4188
4189 /**
4190 * Add any touchable views that are descendants of this view (possibly
4191 * including this view if it is touchable itself) to views.
4192 *
4193 * @param views Touchable views found so far
4194 */
4195 public void addTouchables(ArrayList<View> views) {
4196 final int viewFlags = mViewFlags;
4197
4198 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
4199 && (viewFlags & ENABLED_MASK) == ENABLED) {
4200 views.add(this);
4201 }
4202 }
4203
4204 /**
4205 * Call this to try to give focus to a specific view or to one of its
4206 * descendants.
4207 *
4208 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4209 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4210 * while the device is in touch mode.
4211 *
4212 * See also {@link #focusSearch}, which is what you call to say that you
4213 * have focus, and you want your parent to look for the next one.
4214 *
4215 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4216 * {@link #FOCUS_DOWN} and <code>null</code>.
4217 *
4218 * @return Whether this view or one of its descendants actually took focus.
4219 */
4220 public final boolean requestFocus() {
4221 return requestFocus(View.FOCUS_DOWN);
4222 }
4223
4224
4225 /**
4226 * Call this to try to give focus to a specific view or to one of its
4227 * descendants and give it a hint about what direction focus is heading.
4228 *
4229 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4230 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4231 * while the device is in touch mode.
4232 *
4233 * See also {@link #focusSearch}, which is what you call to say that you
4234 * have focus, and you want your parent to look for the next one.
4235 *
4236 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4237 * <code>null</code> set for the previously focused rectangle.
4238 *
4239 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4240 * @return Whether this view or one of its descendants actually took focus.
4241 */
4242 public final boolean requestFocus(int direction) {
4243 return requestFocus(direction, null);
4244 }
4245
4246 /**
4247 * Call this to try to give focus to a specific view or to one of its descendants
4248 * and give it hints about the direction and a specific rectangle that the focus
4249 * is coming from. The rectangle can help give larger views a finer grained hint
4250 * about where focus is coming from, and therefore, where to show selection, or
4251 * forward focus change internally.
4252 *
4253 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4254 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4255 * while the device is in touch mode.
4256 *
4257 * A View will not take focus if it is not visible.
4258 *
4259 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
4260 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4261 *
4262 * See also {@link #focusSearch}, which is what you call to say that you
4263 * have focus, and you want your parent to look for the next one.
4264 *
4265 * You may wish to override this method if your custom {@link View} has an internal
4266 * {@link View} that it wishes to forward the request to.
4267 *
4268 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4269 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4270 * to give a finer grained hint about where focus is coming from. May be null
4271 * if there is no hint.
4272 * @return Whether this view or one of its descendants actually took focus.
4273 */
4274 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4275 // need to be focusable
4276 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4277 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4278 return false;
4279 }
4280
4281 // need to be focusable in touch mode if in touch mode
4282 if (isInTouchMode() &&
4283 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4284 return false;
4285 }
4286
4287 // need to not have any parents blocking us
4288 if (hasAncestorThatBlocksDescendantFocus()) {
4289 return false;
4290 }
4291
4292 handleFocusGainInternal(direction, previouslyFocusedRect);
4293 return true;
4294 }
4295
Christopher Tate2c095f32010-10-04 14:13:40 -07004296 /** Gets the ViewRoot, or null if not attached. */
4297 /*package*/ ViewRoot getViewRoot() {
4298 View root = getRootView();
4299 return root != null ? (ViewRoot)root.getParent() : null;
4300 }
4301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 /**
4303 * Call this to try to give focus to a specific view or to one of its descendants. This is a
4304 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4305 * touch mode to request focus when they are touched.
4306 *
4307 * @return Whether this view or one of its descendants actually took focus.
4308 *
4309 * @see #isInTouchMode()
4310 *
4311 */
4312 public final boolean requestFocusFromTouch() {
4313 // Leave touch mode if we need to
4314 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07004315 ViewRoot viewRoot = getViewRoot();
4316 if (viewRoot != null) {
4317 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 }
4319 }
4320 return requestFocus(View.FOCUS_DOWN);
4321 }
4322
4323 /**
4324 * @return Whether any ancestor of this view blocks descendant focus.
4325 */
4326 private boolean hasAncestorThatBlocksDescendantFocus() {
4327 ViewParent ancestor = mParent;
4328 while (ancestor instanceof ViewGroup) {
4329 final ViewGroup vgAncestor = (ViewGroup) ancestor;
4330 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4331 return true;
4332 } else {
4333 ancestor = vgAncestor.getParent();
4334 }
4335 }
4336 return false;
4337 }
4338
4339 /**
Romain Guya440b002010-02-24 15:57:54 -08004340 * @hide
4341 */
4342 public void dispatchStartTemporaryDetach() {
4343 onStartTemporaryDetach();
4344 }
4345
4346 /**
4347 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004348 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4349 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004350 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004351 */
4352 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004353 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004354 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004355 }
4356
4357 /**
4358 * @hide
4359 */
4360 public void dispatchFinishTemporaryDetach() {
4361 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 }
Romain Guy8506ab42009-06-11 17:35:47 -07004363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 /**
4365 * Called after {@link #onStartTemporaryDetach} when the container is done
4366 * changing the view.
4367 */
4368 public void onFinishTemporaryDetach() {
4369 }
Romain Guy8506ab42009-06-11 17:35:47 -07004370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 /**
4372 * capture information of this view for later analysis: developement only
4373 * check dynamic switch to make sure we only dump view
4374 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4375 */
4376 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004377 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 return;
4379 }
4380 ViewDebug.dumpCapturedView(subTag, v);
4381 }
4382
4383 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004384 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4385 * for this view's window. Returns null if the view is not currently attached
4386 * to the window. Normally you will not need to use this directly, but
4387 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4388 */
4389 public KeyEvent.DispatcherState getKeyDispatcherState() {
4390 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4391 }
4392
4393 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 * Dispatch a key event before it is processed by any input method
4395 * associated with the view hierarchy. This can be used to intercept
4396 * key events in special situations before the IME consumes them; a
4397 * typical example would be handling the BACK key to update the application's
4398 * UI instead of allowing the IME to see it and close itself.
4399 *
4400 * @param event The key event to be dispatched.
4401 * @return True if the event was handled, false otherwise.
4402 */
4403 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4404 return onKeyPreIme(event.getKeyCode(), event);
4405 }
4406
4407 /**
4408 * Dispatch a key event to the next view on the focus path. This path runs
4409 * from the top of the view tree down to the currently focused view. If this
4410 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4411 * the next node down the focus path. This method also fires any key
4412 * listeners.
4413 *
4414 * @param event The key event to be dispatched.
4415 * @return True if the event was handled, false otherwise.
4416 */
4417 public boolean dispatchKeyEvent(KeyEvent event) {
4418 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004419
Romain Guyf607bdc2010-09-10 19:20:06 -07004420 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004421 if (android.util.Config.LOGV) {
4422 captureViewInfo("captureViewKeyEvent", this);
4423 }
4424
Romain Guyf607bdc2010-09-10 19:20:06 -07004425 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004426 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4427 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4428 return true;
4429 }
4430
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004431 return event.dispatch(this, mAttachInfo != null
4432 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004433 }
4434
4435 /**
4436 * Dispatches a key shortcut event.
4437 *
4438 * @param event The key event to be dispatched.
4439 * @return True if the event was handled by the view, false otherwise.
4440 */
4441 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4442 return onKeyShortcut(event.getKeyCode(), event);
4443 }
4444
4445 /**
4446 * Pass the touch screen motion event down to the target view, or this
4447 * view if it is the target.
4448 *
4449 * @param event The motion event to be dispatched.
4450 * @return True if the event was handled by the view, false otherwise.
4451 */
4452 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004453 if (!onFilterTouchEventForSecurity(event)) {
4454 return false;
4455 }
4456
Romain Guyf607bdc2010-09-10 19:20:06 -07004457 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004458 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4459 mOnTouchListener.onTouch(this, event)) {
4460 return true;
4461 }
4462 return onTouchEvent(event);
4463 }
4464
4465 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004466 * Filter the touch event to apply security policies.
4467 *
4468 * @param event The motion event to be filtered.
4469 * @return True if the event should be dispatched, false if the event should be dropped.
4470 *
4471 * @see #getFilterTouchesWhenObscured
4472 */
4473 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004474 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004475 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4476 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4477 // Window is obscured, drop this touch.
4478 return false;
4479 }
4480 return true;
4481 }
4482
4483 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484 * Pass a trackball motion event down to the focused view.
4485 *
4486 * @param event The motion event to be dispatched.
4487 * @return True if the event was handled by the view, false otherwise.
4488 */
4489 public boolean dispatchTrackballEvent(MotionEvent event) {
4490 //Log.i("view", "view=" + this + ", " + event.toString());
4491 return onTrackballEvent(event);
4492 }
4493
4494 /**
4495 * Called when the window containing this view gains or loses window focus.
4496 * ViewGroups should override to route to their children.
4497 *
4498 * @param hasFocus True if the window containing this view now has focus,
4499 * false otherwise.
4500 */
4501 public void dispatchWindowFocusChanged(boolean hasFocus) {
4502 onWindowFocusChanged(hasFocus);
4503 }
4504
4505 /**
4506 * Called when the window containing this view gains or loses focus. Note
4507 * that this is separate from view focus: to receive key events, both
4508 * your view and its window must have focus. If a window is displayed
4509 * on top of yours that takes input focus, then your own window will lose
4510 * focus but the view focus will remain unchanged.
4511 *
4512 * @param hasWindowFocus True if the window containing this view now has
4513 * focus, false otherwise.
4514 */
4515 public void onWindowFocusChanged(boolean hasWindowFocus) {
4516 InputMethodManager imm = InputMethodManager.peekInstance();
4517 if (!hasWindowFocus) {
4518 if (isPressed()) {
4519 setPressed(false);
4520 }
4521 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4522 imm.focusOut(this);
4523 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004524 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004525 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004526 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4528 imm.focusIn(this);
4529 }
4530 refreshDrawableState();
4531 }
4532
4533 /**
4534 * Returns true if this view is in a window that currently has window focus.
4535 * Note that this is not the same as the view itself having focus.
4536 *
4537 * @return True if this view is in a window that currently has window focus.
4538 */
4539 public boolean hasWindowFocus() {
4540 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4541 }
4542
4543 /**
Adam Powell326d8082009-12-09 15:10:07 -08004544 * Dispatch a view visibility change down the view hierarchy.
4545 * ViewGroups should override to route to their children.
4546 * @param changedView The view whose visibility changed. Could be 'this' or
4547 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004548 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4549 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004550 */
4551 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4552 onVisibilityChanged(changedView, visibility);
4553 }
4554
4555 /**
4556 * Called when the visibility of the view or an ancestor of the view is changed.
4557 * @param changedView The view whose visibility changed. Could be 'this' or
4558 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004559 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4560 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004561 */
4562 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004563 if (visibility == VISIBLE) {
4564 if (mAttachInfo != null) {
4565 initialAwakenScrollBars();
4566 } else {
4567 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4568 }
4569 }
Adam Powell326d8082009-12-09 15:10:07 -08004570 }
4571
4572 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004573 * Dispatch a hint about whether this view is displayed. For instance, when
4574 * a View moves out of the screen, it might receives a display hint indicating
4575 * the view is not displayed. Applications should not <em>rely</em> on this hint
4576 * as there is no guarantee that they will receive one.
4577 *
4578 * @param hint A hint about whether or not this view is displayed:
4579 * {@link #VISIBLE} or {@link #INVISIBLE}.
4580 */
4581 public void dispatchDisplayHint(int hint) {
4582 onDisplayHint(hint);
4583 }
4584
4585 /**
4586 * Gives this view a hint about whether is displayed or not. For instance, when
4587 * a View moves out of the screen, it might receives a display hint indicating
4588 * the view is not displayed. Applications should not <em>rely</em> on this hint
4589 * as there is no guarantee that they will receive one.
4590 *
4591 * @param hint A hint about whether or not this view is displayed:
4592 * {@link #VISIBLE} or {@link #INVISIBLE}.
4593 */
4594 protected void onDisplayHint(int hint) {
4595 }
4596
4597 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004598 * Dispatch a window visibility change down the view hierarchy.
4599 * ViewGroups should override to route to their children.
4600 *
4601 * @param visibility The new visibility of the window.
4602 *
4603 * @see #onWindowVisibilityChanged
4604 */
4605 public void dispatchWindowVisibilityChanged(int visibility) {
4606 onWindowVisibilityChanged(visibility);
4607 }
4608
4609 /**
4610 * Called when the window containing has change its visibility
4611 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4612 * that this tells you whether or not your window is being made visible
4613 * to the window manager; this does <em>not</em> tell you whether or not
4614 * your window is obscured by other windows on the screen, even if it
4615 * is itself visible.
4616 *
4617 * @param visibility The new visibility of the window.
4618 */
4619 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004620 if (visibility == VISIBLE) {
4621 initialAwakenScrollBars();
4622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004623 }
4624
4625 /**
4626 * Returns the current visibility of the window this view is attached to
4627 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4628 *
4629 * @return Returns the current visibility of the view's window.
4630 */
4631 public int getWindowVisibility() {
4632 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4633 }
4634
4635 /**
4636 * Retrieve the overall visible display size in which the window this view is
4637 * attached to has been positioned in. This takes into account screen
4638 * decorations above the window, for both cases where the window itself
4639 * is being position inside of them or the window is being placed under
4640 * then and covered insets are used for the window to position its content
4641 * inside. In effect, this tells you the available area where content can
4642 * be placed and remain visible to users.
4643 *
4644 * <p>This function requires an IPC back to the window manager to retrieve
4645 * the requested information, so should not be used in performance critical
4646 * code like drawing.
4647 *
4648 * @param outRect Filled in with the visible display frame. If the view
4649 * is not attached to a window, this is simply the raw display size.
4650 */
4651 public void getWindowVisibleDisplayFrame(Rect outRect) {
4652 if (mAttachInfo != null) {
4653 try {
4654 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4655 } catch (RemoteException e) {
4656 return;
4657 }
4658 // XXX This is really broken, and probably all needs to be done
4659 // in the window manager, and we need to know more about whether
4660 // we want the area behind or in front of the IME.
4661 final Rect insets = mAttachInfo.mVisibleInsets;
4662 outRect.left += insets.left;
4663 outRect.top += insets.top;
4664 outRect.right -= insets.right;
4665 outRect.bottom -= insets.bottom;
4666 return;
4667 }
4668 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4669 outRect.set(0, 0, d.getWidth(), d.getHeight());
4670 }
4671
4672 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004673 * Dispatch a notification about a resource configuration change down
4674 * the view hierarchy.
4675 * ViewGroups should override to route to their children.
4676 *
4677 * @param newConfig The new resource configuration.
4678 *
4679 * @see #onConfigurationChanged
4680 */
4681 public void dispatchConfigurationChanged(Configuration newConfig) {
4682 onConfigurationChanged(newConfig);
4683 }
4684
4685 /**
4686 * Called when the current configuration of the resources being used
4687 * by the application have changed. You can use this to decide when
4688 * to reload resources that can changed based on orientation and other
4689 * configuration characterstics. You only need to use this if you are
4690 * not relying on the normal {@link android.app.Activity} mechanism of
4691 * recreating the activity instance upon a configuration change.
4692 *
4693 * @param newConfig The new resource configuration.
4694 */
4695 protected void onConfigurationChanged(Configuration newConfig) {
4696 }
4697
4698 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004699 * Private function to aggregate all per-view attributes in to the view
4700 * root.
4701 */
4702 void dispatchCollectViewAttributes(int visibility) {
4703 performCollectViewAttributes(visibility);
4704 }
4705
4706 void performCollectViewAttributes(int visibility) {
4707 //noinspection PointlessBitwiseExpression
4708 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4709 == (VISIBLE | KEEP_SCREEN_ON)) {
4710 mAttachInfo.mKeepScreenOn = true;
4711 }
4712 }
4713
4714 void needGlobalAttributesUpdate(boolean force) {
4715 AttachInfo ai = mAttachInfo;
4716 if (ai != null) {
4717 if (ai.mKeepScreenOn || force) {
4718 ai.mRecomputeGlobalAttributes = true;
4719 }
4720 }
4721 }
4722
4723 /**
4724 * Returns whether the device is currently in touch mode. Touch mode is entered
4725 * once the user begins interacting with the device by touch, and affects various
4726 * things like whether focus is always visible to the user.
4727 *
4728 * @return Whether the device is in touch mode.
4729 */
4730 @ViewDebug.ExportedProperty
4731 public boolean isInTouchMode() {
4732 if (mAttachInfo != null) {
4733 return mAttachInfo.mInTouchMode;
4734 } else {
4735 return ViewRoot.isInTouchMode();
4736 }
4737 }
4738
4739 /**
4740 * Returns the context the view is running in, through which it can
4741 * access the current theme, resources, etc.
4742 *
4743 * @return The view's Context.
4744 */
4745 @ViewDebug.CapturedViewProperty
4746 public final Context getContext() {
4747 return mContext;
4748 }
4749
4750 /**
4751 * Handle a key event before it is processed by any input method
4752 * associated with the view hierarchy. This can be used to intercept
4753 * key events in special situations before the IME consumes them; a
4754 * typical example would be handling the BACK key to update the application's
4755 * UI instead of allowing the IME to see it and close itself.
4756 *
4757 * @param keyCode The value in event.getKeyCode().
4758 * @param event Description of the key event.
4759 * @return If you handled the event, return true. If you want to allow the
4760 * event to be handled by the next receiver, return false.
4761 */
4762 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4763 return false;
4764 }
4765
4766 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004767 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
4768 * KeyEvent.Callback.onKeyDown()}: perform press of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4770 * is released, if the view is enabled and clickable.
4771 *
4772 * @param keyCode A key code that represents the button pressed, from
4773 * {@link android.view.KeyEvent}.
4774 * @param event The KeyEvent object that defines the button action.
4775 */
4776 public boolean onKeyDown(int keyCode, KeyEvent event) {
4777 boolean result = false;
4778
4779 switch (keyCode) {
4780 case KeyEvent.KEYCODE_DPAD_CENTER:
4781 case KeyEvent.KEYCODE_ENTER: {
4782 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4783 return true;
4784 }
4785 // Long clickable items don't necessarily have to be clickable
4786 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4787 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4788 (event.getRepeatCount() == 0)) {
4789 setPressed(true);
4790 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004791 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004792 }
4793 return true;
4794 }
4795 break;
4796 }
4797 }
4798 return result;
4799 }
4800
4801 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004802 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4803 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4804 * the event).
4805 */
4806 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4807 return false;
4808 }
4809
4810 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004811 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
4812 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004813 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4814 * {@link KeyEvent#KEYCODE_ENTER} is released.
4815 *
4816 * @param keyCode A key code that represents the button pressed, from
4817 * {@link android.view.KeyEvent}.
4818 * @param event The KeyEvent object that defines the button action.
4819 */
4820 public boolean onKeyUp(int keyCode, KeyEvent event) {
4821 boolean result = false;
4822
4823 switch (keyCode) {
4824 case KeyEvent.KEYCODE_DPAD_CENTER:
4825 case KeyEvent.KEYCODE_ENTER: {
4826 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4827 return true;
4828 }
4829 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4830 setPressed(false);
4831
4832 if (!mHasPerformedLongPress) {
4833 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004834 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004835
4836 result = performClick();
4837 }
4838 }
4839 break;
4840 }
4841 }
4842 return result;
4843 }
4844
4845 /**
4846 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4847 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4848 * the event).
4849 *
4850 * @param keyCode A key code that represents the button pressed, from
4851 * {@link android.view.KeyEvent}.
4852 * @param repeatCount The number of times the action was made.
4853 * @param event The KeyEvent object that defines the button action.
4854 */
4855 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4856 return false;
4857 }
4858
4859 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08004860 * Called on the focused view when a key shortcut event is not handled.
4861 * Override this method to implement local key shortcuts for the View.
4862 * Key shortcuts can also be implemented by setting the
4863 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004864 *
4865 * @param keyCode The value in event.getKeyCode().
4866 * @param event Description of the key event.
4867 * @return If you handled the event, return true. If you want to allow the
4868 * event to be handled by the next receiver, return false.
4869 */
4870 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4871 return false;
4872 }
4873
4874 /**
4875 * Check whether the called view is a text editor, in which case it
4876 * would make sense to automatically display a soft input window for
4877 * it. Subclasses should override this if they implement
4878 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004879 * a call on that method would return a non-null InputConnection, and
4880 * they are really a first-class editor that the user would normally
4881 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004882 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004883 * <p>The default implementation always returns false. This does
4884 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4885 * will not be called or the user can not otherwise perform edits on your
4886 * view; it is just a hint to the system that this is not the primary
4887 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004888 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004889 * @return Returns true if this view is a text editor, else false.
4890 */
4891 public boolean onCheckIsTextEditor() {
4892 return false;
4893 }
Romain Guy8506ab42009-06-11 17:35:47 -07004894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 /**
4896 * Create a new InputConnection for an InputMethod to interact
4897 * with the view. The default implementation returns null, since it doesn't
4898 * support input methods. You can override this to implement such support.
4899 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004900 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004901 * <p>When implementing this, you probably also want to implement
4902 * {@link #onCheckIsTextEditor()} to indicate you will return a
4903 * non-null InputConnection.
4904 *
4905 * @param outAttrs Fill in with attribute information about the connection.
4906 */
4907 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4908 return null;
4909 }
4910
4911 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004912 * Called by the {@link android.view.inputmethod.InputMethodManager}
4913 * when a view who is not the current
4914 * input connection target is trying to make a call on the manager. The
4915 * default implementation returns false; you can override this to return
4916 * true for certain views if you are performing InputConnection proxying
4917 * to them.
4918 * @param view The View that is making the InputMethodManager call.
4919 * @return Return true to allow the call, false to reject.
4920 */
4921 public boolean checkInputConnectionProxy(View view) {
4922 return false;
4923 }
Romain Guy8506ab42009-06-11 17:35:47 -07004924
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004925 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004926 * Show the context menu for this view. It is not safe to hold on to the
4927 * menu after returning from this method.
4928 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004929 * You should normally not overload this method. Overload
4930 * {@link #onCreateContextMenu(ContextMenu)} or define an
4931 * {@link OnCreateContextMenuListener} to add items to the context menu.
4932 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004933 * @param menu The context menu to populate
4934 */
4935 public void createContextMenu(ContextMenu menu) {
4936 ContextMenuInfo menuInfo = getContextMenuInfo();
4937
4938 // Sets the current menu info so all items added to menu will have
4939 // my extra info set.
4940 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4941
4942 onCreateContextMenu(menu);
4943 if (mOnCreateContextMenuListener != null) {
4944 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4945 }
4946
4947 // Clear the extra information so subsequent items that aren't mine don't
4948 // have my extra info.
4949 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4950
4951 if (mParent != null) {
4952 mParent.createContextMenu(menu);
4953 }
4954 }
4955
4956 /**
4957 * Views should implement this if they have extra information to associate
4958 * with the context menu. The return result is supplied as a parameter to
4959 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4960 * callback.
4961 *
4962 * @return Extra information about the item for which the context menu
4963 * should be shown. This information will vary across different
4964 * subclasses of View.
4965 */
4966 protected ContextMenuInfo getContextMenuInfo() {
4967 return null;
4968 }
4969
4970 /**
4971 * Views should implement this if the view itself is going to add items to
4972 * the context menu.
4973 *
4974 * @param menu the context menu to populate
4975 */
4976 protected void onCreateContextMenu(ContextMenu menu) {
4977 }
4978
4979 /**
4980 * Implement this method to handle trackball motion events. The
4981 * <em>relative</em> movement of the trackball since the last event
4982 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4983 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4984 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4985 * they will often be fractional values, representing the more fine-grained
4986 * movement information available from a trackball).
4987 *
4988 * @param event The motion event.
4989 * @return True if the event was handled, false otherwise.
4990 */
4991 public boolean onTrackballEvent(MotionEvent event) {
4992 return false;
4993 }
4994
4995 /**
4996 * Implement this method to handle touch screen motion events.
4997 *
4998 * @param event The motion event.
4999 * @return True if the event was handled, false otherwise.
5000 */
5001 public boolean onTouchEvent(MotionEvent event) {
5002 final int viewFlags = mViewFlags;
5003
5004 if ((viewFlags & ENABLED_MASK) == DISABLED) {
5005 // A disabled view that is clickable still consumes the touch
5006 // events, it just doesn't respond to them.
5007 return (((viewFlags & CLICKABLE) == CLICKABLE ||
5008 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
5009 }
5010
5011 if (mTouchDelegate != null) {
5012 if (mTouchDelegate.onTouchEvent(event)) {
5013 return true;
5014 }
5015 }
5016
5017 if (((viewFlags & CLICKABLE) == CLICKABLE ||
5018 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
5019 switch (event.getAction()) {
5020 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08005021 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
5022 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 // take focus if we don't have it already and we should in
5024 // touch mode.
5025 boolean focusTaken = false;
5026 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
5027 focusTaken = requestFocus();
5028 }
5029
5030 if (!mHasPerformedLongPress) {
5031 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05005032 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005033
5034 // Only perform take click actions if we were in the pressed state
5035 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08005036 // Use a Runnable and post this rather than calling
5037 // performClick directly. This lets other visual state
5038 // of the view update before click actions start.
5039 if (mPerformClick == null) {
5040 mPerformClick = new PerformClick();
5041 }
5042 if (!post(mPerformClick)) {
5043 performClick();
5044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005045 }
5046 }
5047
5048 if (mUnsetPressedState == null) {
5049 mUnsetPressedState = new UnsetPressedState();
5050 }
5051
Adam Powelle14579b2009-12-16 18:39:52 -08005052 if (prepressed) {
5053 mPrivateFlags |= PRESSED;
5054 refreshDrawableState();
5055 postDelayed(mUnsetPressedState,
5056 ViewConfiguration.getPressedStateDuration());
5057 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005058 // If the post failed, unpress right now
5059 mUnsetPressedState.run();
5060 }
Adam Powelle14579b2009-12-16 18:39:52 -08005061 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 }
5063 break;
5064
5065 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08005066 if (mPendingCheckForTap == null) {
5067 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005068 }
Adam Powelle14579b2009-12-16 18:39:52 -08005069 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08005070 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08005071 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 break;
5073
5074 case MotionEvent.ACTION_CANCEL:
5075 mPrivateFlags &= ~PRESSED;
5076 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08005077 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005078 break;
5079
5080 case MotionEvent.ACTION_MOVE:
5081 final int x = (int) event.getX();
5082 final int y = (int) event.getY();
5083
5084 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07005085 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005086 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08005087 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005088 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08005089 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05005090 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091
5092 // Need to switch from pressed to not pressed
5093 mPrivateFlags &= ~PRESSED;
5094 refreshDrawableState();
5095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005096 }
5097 break;
5098 }
5099 return true;
5100 }
5101
5102 return false;
5103 }
5104
5105 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05005106 * Remove the longpress detection timer.
5107 */
5108 private void removeLongPressCallback() {
5109 if (mPendingCheckForLongPress != null) {
5110 removeCallbacks(mPendingCheckForLongPress);
5111 }
5112 }
Adam Powelle14579b2009-12-16 18:39:52 -08005113
5114 /**
Romain Guya440b002010-02-24 15:57:54 -08005115 * Remove the prepress detection timer.
5116 */
5117 private void removeUnsetPressCallback() {
5118 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
5119 setPressed(false);
5120 removeCallbacks(mUnsetPressedState);
5121 }
5122 }
5123
5124 /**
Adam Powelle14579b2009-12-16 18:39:52 -08005125 * Remove the tap detection timer.
5126 */
5127 private void removeTapCallback() {
5128 if (mPendingCheckForTap != null) {
5129 mPrivateFlags &= ~PREPRESSED;
5130 removeCallbacks(mPendingCheckForTap);
5131 }
5132 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05005133
5134 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005135 * Cancels a pending long press. Your subclass can use this if you
5136 * want the context menu to come up if the user presses and holds
5137 * at the same place, but you don't want it to come up if they press
5138 * and then move around enough to cause scrolling.
5139 */
5140 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05005141 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08005142
5143 /*
5144 * The prepressed state handled by the tap callback is a display
5145 * construct, but the tap callback will post a long press callback
5146 * less its own timeout. Remove it here.
5147 */
5148 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005149 }
5150
5151 /**
5152 * Sets the TouchDelegate for this View.
5153 */
5154 public void setTouchDelegate(TouchDelegate delegate) {
5155 mTouchDelegate = delegate;
5156 }
5157
5158 /**
5159 * Gets the TouchDelegate for this View.
5160 */
5161 public TouchDelegate getTouchDelegate() {
5162 return mTouchDelegate;
5163 }
5164
5165 /**
5166 * Set flags controlling behavior of this view.
5167 *
5168 * @param flags Constant indicating the value which should be set
5169 * @param mask Constant indicating the bit range that should be changed
5170 */
5171 void setFlags(int flags, int mask) {
5172 int old = mViewFlags;
5173 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
5174
5175 int changed = mViewFlags ^ old;
5176 if (changed == 0) {
5177 return;
5178 }
5179 int privateFlags = mPrivateFlags;
5180
5181 /* Check if the FOCUSABLE bit has changed */
5182 if (((changed & FOCUSABLE_MASK) != 0) &&
5183 ((privateFlags & HAS_BOUNDS) !=0)) {
5184 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
5185 && ((privateFlags & FOCUSED) != 0)) {
5186 /* Give up focus if we are no longer focusable */
5187 clearFocus();
5188 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
5189 && ((privateFlags & FOCUSED) == 0)) {
5190 /*
5191 * Tell the view system that we are now available to take focus
5192 * if no one else already has it.
5193 */
5194 if (mParent != null) mParent.focusableViewAvailable(this);
5195 }
5196 }
5197
5198 if ((flags & VISIBILITY_MASK) == VISIBLE) {
5199 if ((changed & VISIBILITY_MASK) != 0) {
5200 /*
5201 * If this view is becoming visible, set the DRAWN flag so that
5202 * the next invalidate() will not be skipped.
5203 */
5204 mPrivateFlags |= DRAWN;
5205
5206 needGlobalAttributesUpdate(true);
5207
5208 // a view becoming visible is worth notifying the parent
5209 // about in case nothing has focus. even if this specific view
5210 // isn't focusable, it may contain something that is, so let
5211 // the root view try to give this focus if nothing else does.
5212 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
5213 mParent.focusableViewAvailable(this);
5214 }
5215 }
5216 }
5217
5218 /* Check if the GONE bit has changed */
5219 if ((changed & GONE) != 0) {
5220 needGlobalAttributesUpdate(false);
5221 requestLayout();
5222 invalidate();
5223
Romain Guyecd80ee2009-12-03 17:13:02 -08005224 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
5225 if (hasFocus()) clearFocus();
5226 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005227 }
5228 if (mAttachInfo != null) {
5229 mAttachInfo.mViewVisibilityChanged = true;
5230 }
5231 }
5232
5233 /* Check if the VISIBLE bit has changed */
5234 if ((changed & INVISIBLE) != 0) {
5235 needGlobalAttributesUpdate(false);
5236 invalidate();
5237
5238 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
5239 // root view becoming invisible shouldn't clear focus
5240 if (getRootView() != this) {
5241 clearFocus();
5242 }
5243 }
5244 if (mAttachInfo != null) {
5245 mAttachInfo.mViewVisibilityChanged = true;
5246 }
5247 }
5248
Adam Powell326d8082009-12-09 15:10:07 -08005249 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07005250 if (mParent instanceof ViewGroup) {
5251 ((ViewGroup)mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
5252 }
Adam Powell326d8082009-12-09 15:10:07 -08005253 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
5254 }
5255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
5257 destroyDrawingCache();
5258 }
5259
5260 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
5261 destroyDrawingCache();
5262 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5263 }
5264
5265 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
5266 destroyDrawingCache();
5267 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5268 }
5269
5270 if ((changed & DRAW_MASK) != 0) {
5271 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
5272 if (mBGDrawable != null) {
5273 mPrivateFlags &= ~SKIP_DRAW;
5274 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
5275 } else {
5276 mPrivateFlags |= SKIP_DRAW;
5277 }
5278 } else {
5279 mPrivateFlags &= ~SKIP_DRAW;
5280 }
5281 requestLayout();
5282 invalidate();
5283 }
5284
5285 if ((changed & KEEP_SCREEN_ON) != 0) {
5286 if (mParent != null) {
5287 mParent.recomputeViewAttributes(this);
5288 }
5289 }
5290 }
5291
5292 /**
5293 * Change the view's z order in the tree, so it's on top of other sibling
5294 * views
5295 */
5296 public void bringToFront() {
5297 if (mParent != null) {
5298 mParent.bringChildToFront(this);
5299 }
5300 }
5301
5302 /**
5303 * This is called in response to an internal scroll in this view (i.e., the
5304 * view scrolled its own contents). This is typically as a result of
5305 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
5306 * called.
5307 *
5308 * @param l Current horizontal scroll origin.
5309 * @param t Current vertical scroll origin.
5310 * @param oldl Previous horizontal scroll origin.
5311 * @param oldt Previous vertical scroll origin.
5312 */
5313 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5314 mBackgroundSizeChanged = true;
5315
5316 final AttachInfo ai = mAttachInfo;
5317 if (ai != null) {
5318 ai.mViewScrollChanged = true;
5319 }
5320 }
5321
5322 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005323 * Interface definition for a callback to be invoked when the layout bounds of a view
5324 * changes due to layout processing.
5325 */
5326 public interface OnLayoutChangeListener {
5327 /**
5328 * Called when the focus state of a view has changed.
5329 *
5330 * @param v The view whose state has changed.
5331 * @param left The new value of the view's left property.
5332 * @param top The new value of the view's top property.
5333 * @param right The new value of the view's right property.
5334 * @param bottom The new value of the view's bottom property.
5335 * @param oldLeft The previous value of the view's left property.
5336 * @param oldTop The previous value of the view's top property.
5337 * @param oldRight The previous value of the view's right property.
5338 * @param oldBottom The previous value of the view's bottom property.
5339 */
5340 void onLayoutChange(View v, int left, int top, int right, int bottom,
5341 int oldLeft, int oldTop, int oldRight, int oldBottom);
5342 }
5343
5344 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345 * This is called during layout when the size of this view has changed. If
5346 * you were just added to the view hierarchy, you're called with the old
5347 * values of 0.
5348 *
5349 * @param w Current width of this view.
5350 * @param h Current height of this view.
5351 * @param oldw Old width of this view.
5352 * @param oldh Old height of this view.
5353 */
5354 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5355 }
5356
5357 /**
5358 * Called by draw to draw the child views. This may be overridden
5359 * by derived classes to gain control just before its children are drawn
5360 * (but after its own view has been drawn).
5361 * @param canvas the canvas on which to draw the view
5362 */
5363 protected void dispatchDraw(Canvas canvas) {
5364 }
5365
5366 /**
5367 * Gets the parent of this view. Note that the parent is a
5368 * ViewParent and not necessarily a View.
5369 *
5370 * @return Parent of this view.
5371 */
5372 public final ViewParent getParent() {
5373 return mParent;
5374 }
5375
5376 /**
5377 * Return the scrolled left position of this view. This is the left edge of
5378 * the displayed part of your view. You do not need to draw any pixels
5379 * farther left, since those are outside of the frame of your view on
5380 * screen.
5381 *
5382 * @return The left edge of the displayed part of your view, in pixels.
5383 */
5384 public final int getScrollX() {
5385 return mScrollX;
5386 }
5387
5388 /**
5389 * Return the scrolled top position of this view. This is the top edge of
5390 * the displayed part of your view. You do not need to draw any pixels above
5391 * it, since those are outside of the frame of your view on screen.
5392 *
5393 * @return The top edge of the displayed part of your view, in pixels.
5394 */
5395 public final int getScrollY() {
5396 return mScrollY;
5397 }
5398
5399 /**
5400 * Return the width of the your view.
5401 *
5402 * @return The width of your view, in pixels.
5403 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005404 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005405 public final int getWidth() {
5406 return mRight - mLeft;
5407 }
5408
5409 /**
5410 * Return the height of your view.
5411 *
5412 * @return The height of your view, in pixels.
5413 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005414 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 public final int getHeight() {
5416 return mBottom - mTop;
5417 }
5418
5419 /**
5420 * Return the visible drawing bounds of your view. Fills in the output
5421 * rectangle with the values from getScrollX(), getScrollY(),
5422 * getWidth(), and getHeight().
5423 *
5424 * @param outRect The (scrolled) drawing bounds of the view.
5425 */
5426 public void getDrawingRect(Rect outRect) {
5427 outRect.left = mScrollX;
5428 outRect.top = mScrollY;
5429 outRect.right = mScrollX + (mRight - mLeft);
5430 outRect.bottom = mScrollY + (mBottom - mTop);
5431 }
5432
5433 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005434 * Like {@link #getMeasuredWidthAndState()}, but only returns the
5435 * raw width component (that is the result is masked by
5436 * {@link #MEASURED_SIZE_MASK}).
5437 *
5438 * @return The raw measured width of this view.
5439 */
5440 public final int getMeasuredWidth() {
5441 return mMeasuredWidth & MEASURED_SIZE_MASK;
5442 }
5443
5444 /**
5445 * Return the full width measurement information for this view as computed
5446 * by the most recent call to {@link #measure}. This result is a bit mask
5447 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 * This should be used during measurement and layout calculations only. Use
5449 * {@link #getWidth()} to see how wide a view is after layout.
5450 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005451 * @return The measured width of this view as a bit mask.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08005453 public final int getMeasuredWidthAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 return mMeasuredWidth;
5455 }
5456
5457 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005458 * Like {@link #getMeasuredHeightAndState()}, but only returns the
5459 * raw width component (that is the result is masked by
5460 * {@link #MEASURED_SIZE_MASK}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005461 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005462 * @return The raw measured height of this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 */
5464 public final int getMeasuredHeight() {
Dianne Hackborn189ee182010-12-02 21:48:53 -08005465 return mMeasuredHeight & MEASURED_SIZE_MASK;
5466 }
5467
5468 /**
5469 * Return the full height measurement information for this view as computed
5470 * by the most recent call to {@link #measure}. This result is a bit mask
5471 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
5472 * This should be used during measurement and layout calculations only. Use
5473 * {@link #getHeight()} to see how wide a view is after layout.
5474 *
5475 * @return The measured width of this view as a bit mask.
5476 */
5477 public final int getMeasuredHeightAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 return mMeasuredHeight;
5479 }
5480
5481 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005482 * Return only the state bits of {@link #getMeasuredWidthAndState()}
5483 * and {@link #getMeasuredHeightAndState()}, combined into one integer.
5484 * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
5485 * and the height component is at the shifted bits
5486 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
5487 */
5488 public final int getMeasuredState() {
5489 return (mMeasuredWidth&MEASURED_STATE_MASK)
5490 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
5491 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
5492 }
5493
5494 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005495 * The transform matrix of this view, which is calculated based on the current
5496 * roation, scale, and pivot properties.
5497 *
5498 * @see #getRotation()
5499 * @see #getScaleX()
5500 * @see #getScaleY()
5501 * @see #getPivotX()
5502 * @see #getPivotY()
5503 * @return The current transform matrix for the view
5504 */
5505 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005506 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005507 return mMatrix;
5508 }
5509
5510 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005511 * Utility function to determine if the value is far enough away from zero to be
5512 * considered non-zero.
5513 * @param value A floating point value to check for zero-ness
5514 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5515 */
5516 private static boolean nonzero(float value) {
5517 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5518 }
5519
5520 /**
Jeff Brown86671742010-09-30 20:00:15 -07005521 * Returns true if the transform matrix is the identity matrix.
5522 * Recomputes the matrix if necessary.
Romain Guy33e72ae2010-07-17 12:40:29 -07005523 *
5524 * @return True if the transform matrix is the identity matrix, false otherwise.
5525 */
Jeff Brown86671742010-09-30 20:00:15 -07005526 final boolean hasIdentityMatrix() {
5527 updateMatrix();
5528 return mMatrixIsIdentity;
5529 }
5530
5531 /**
5532 * Recomputes the transform matrix if necessary.
5533 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005534 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005535 if (mMatrixDirty) {
5536 // transform-related properties have changed since the last time someone
5537 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005538
5539 // Figure out if we need to update the pivot point
5540 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005541 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005542 mPrevWidth = mRight - mLeft;
5543 mPrevHeight = mBottom - mTop;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -08005544 mPivotX = mPrevWidth / 2f;
5545 mPivotY = mPrevHeight / 2f;
Chet Haasefd2b0022010-08-06 13:08:56 -07005546 }
5547 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005548 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005549 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5550 mMatrix.setTranslate(mTranslationX, mTranslationY);
5551 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5552 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5553 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005554 if (mCamera == null) {
5555 mCamera = new Camera();
5556 matrix3D = new Matrix();
5557 }
5558 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005559 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005560 mCamera.rotateX(mRotationX);
5561 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005562 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005563 mCamera.getMatrix(matrix3D);
5564 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005565 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005566 mMatrix.postConcat(matrix3D);
5567 mCamera.restore();
5568 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005569 mMatrixDirty = false;
5570 mMatrixIsIdentity = mMatrix.isIdentity();
5571 mInverseMatrixDirty = true;
5572 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005573 }
5574
5575 /**
5576 * Utility method to retrieve the inverse of the current mMatrix property.
5577 * We cache the matrix to avoid recalculating it when transform properties
5578 * have not changed.
5579 *
5580 * @return The inverse of the current matrix of this view.
5581 */
Jeff Brown86671742010-09-30 20:00:15 -07005582 final Matrix getInverseMatrix() {
5583 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005584 if (mInverseMatrixDirty) {
5585 if (mInverseMatrix == null) {
5586 mInverseMatrix = new Matrix();
5587 }
5588 mMatrix.invert(mInverseMatrix);
5589 mInverseMatrixDirty = false;
5590 }
5591 return mInverseMatrix;
5592 }
5593
5594 /**
5595 * The degrees that the view is rotated around the pivot point.
5596 *
5597 * @see #getPivotX()
5598 * @see #getPivotY()
5599 * @return The degrees of rotation.
5600 */
5601 public float getRotation() {
5602 return mRotation;
5603 }
5604
5605 /**
Chet Haase897247b2010-09-09 14:54:47 -07005606 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5607 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005608 *
5609 * @param rotation The degrees of rotation.
5610 * @see #getPivotX()
5611 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005612 *
5613 * @attr ref android.R.styleable#View_rotation
Chet Haasec3aa3612010-06-17 08:50:37 -07005614 */
5615 public void setRotation(float rotation) {
5616 if (mRotation != rotation) {
5617 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005618 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005619 mRotation = rotation;
5620 mMatrixDirty = true;
5621 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005622 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005623 }
5624 }
5625
5626 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005627 * The degrees that the view is rotated around the vertical axis through the pivot point.
5628 *
5629 * @see #getPivotX()
5630 * @see #getPivotY()
5631 * @return The degrees of Y rotation.
5632 */
5633 public float getRotationY() {
5634 return mRotationY;
5635 }
5636
5637 /**
Chet Haase897247b2010-09-09 14:54:47 -07005638 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5639 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5640 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005641 *
5642 * @param rotationY The degrees of Y rotation.
5643 * @see #getPivotX()
5644 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005645 *
5646 * @attr ref android.R.styleable#View_rotationY
Chet Haasefd2b0022010-08-06 13:08:56 -07005647 */
5648 public void setRotationY(float rotationY) {
5649 if (mRotationY != rotationY) {
5650 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005651 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005652 mRotationY = rotationY;
5653 mMatrixDirty = true;
5654 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005655 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005656 }
5657 }
5658
5659 /**
5660 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5661 *
5662 * @see #getPivotX()
5663 * @see #getPivotY()
5664 * @return The degrees of X rotation.
5665 */
5666 public float getRotationX() {
5667 return mRotationX;
5668 }
5669
5670 /**
Chet Haase897247b2010-09-09 14:54:47 -07005671 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5672 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5673 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005674 *
5675 * @param rotationX The degrees of X rotation.
5676 * @see #getPivotX()
5677 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005678 *
5679 * @attr ref android.R.styleable#View_rotationX
Chet Haasefd2b0022010-08-06 13:08:56 -07005680 */
5681 public void setRotationX(float rotationX) {
5682 if (mRotationX != rotationX) {
5683 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005684 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005685 mRotationX = rotationX;
5686 mMatrixDirty = true;
5687 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005688 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005689 }
5690 }
5691
5692 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005693 * The amount that the view is scaled in x around the pivot point, as a proportion of
5694 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5695 *
Joe Onorato93162322010-09-16 15:42:01 -04005696 * <p>By default, this is 1.0f.
5697 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005698 * @see #getPivotX()
5699 * @see #getPivotY()
5700 * @return The scaling factor.
5701 */
5702 public float getScaleX() {
5703 return mScaleX;
5704 }
5705
5706 /**
5707 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5708 * the view's unscaled width. A value of 1 means that no scaling is applied.
5709 *
5710 * @param scaleX The scaling factor.
5711 * @see #getPivotX()
5712 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005713 *
5714 * @attr ref android.R.styleable#View_scaleX
Chet Haasec3aa3612010-06-17 08:50:37 -07005715 */
5716 public void setScaleX(float scaleX) {
5717 if (mScaleX != scaleX) {
5718 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005719 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005720 mScaleX = scaleX;
5721 mMatrixDirty = true;
5722 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005723 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005724 }
5725 }
5726
5727 /**
5728 * The amount that the view is scaled in y around the pivot point, as a proportion of
5729 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5730 *
Joe Onorato93162322010-09-16 15:42:01 -04005731 * <p>By default, this is 1.0f.
5732 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005733 * @see #getPivotX()
5734 * @see #getPivotY()
5735 * @return The scaling factor.
5736 */
5737 public float getScaleY() {
5738 return mScaleY;
5739 }
5740
5741 /**
5742 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5743 * the view's unscaled width. A value of 1 means that no scaling is applied.
5744 *
5745 * @param scaleY The scaling factor.
5746 * @see #getPivotX()
5747 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005748 *
5749 * @attr ref android.R.styleable#View_scaleY
Chet Haasec3aa3612010-06-17 08:50:37 -07005750 */
5751 public void setScaleY(float scaleY) {
5752 if (mScaleY != scaleY) {
5753 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005754 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005755 mScaleY = scaleY;
5756 mMatrixDirty = true;
5757 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005758 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005759 }
5760 }
5761
5762 /**
5763 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5764 * and {@link #setScaleX(float) scaled}.
5765 *
5766 * @see #getRotation()
5767 * @see #getScaleX()
5768 * @see #getScaleY()
5769 * @see #getPivotY()
5770 * @return The x location of the pivot point.
5771 */
5772 public float getPivotX() {
5773 return mPivotX;
5774 }
5775
5776 /**
5777 * Sets the x location of the point around which the view is
5778 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005779 * By default, the pivot point is centered on the object.
5780 * Setting this property disables this behavior and causes the view to use only the
5781 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005782 *
5783 * @param pivotX The x location of the pivot point.
5784 * @see #getRotation()
5785 * @see #getScaleX()
5786 * @see #getScaleY()
5787 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005788 *
5789 * @attr ref android.R.styleable#View_transformPivotX
Chet Haasec3aa3612010-06-17 08:50:37 -07005790 */
5791 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005792 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005793 if (mPivotX != pivotX) {
5794 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005795 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005796 mPivotX = pivotX;
5797 mMatrixDirty = true;
5798 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005799 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005800 }
5801 }
5802
5803 /**
5804 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5805 * and {@link #setScaleY(float) scaled}.
5806 *
5807 * @see #getRotation()
5808 * @see #getScaleX()
5809 * @see #getScaleY()
5810 * @see #getPivotY()
5811 * @return The y location of the pivot point.
5812 */
5813 public float getPivotY() {
5814 return mPivotY;
5815 }
5816
5817 /**
5818 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005819 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5820 * Setting this property disables this behavior and causes the view to use only the
5821 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005822 *
5823 * @param pivotY The y location of the pivot point.
5824 * @see #getRotation()
5825 * @see #getScaleX()
5826 * @see #getScaleY()
5827 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005828 *
5829 * @attr ref android.R.styleable#View_transformPivotY
Chet Haasec3aa3612010-06-17 08:50:37 -07005830 */
5831 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005832 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005833 if (mPivotY != pivotY) {
5834 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005835 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005836 mPivotY = pivotY;
5837 mMatrixDirty = true;
5838 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005839 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005840 }
5841 }
5842
5843 /**
5844 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5845 * completely transparent and 1 means the view is completely opaque.
5846 *
Joe Onorato93162322010-09-16 15:42:01 -04005847 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005848 * @return The opacity of the view.
5849 */
5850 public float getAlpha() {
5851 return mAlpha;
5852 }
5853
5854 /**
Romain Guy171c5922011-01-06 10:04:23 -08005855 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5856 * completely transparent and 1 means the view is completely opaque.</p>
5857 *
5858 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
5859 * responsible for applying the opacity itself. Otherwise, calling this method is
5860 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
5861 * setting a hardware layer.</p>
Chet Haasec3aa3612010-06-17 08:50:37 -07005862 *
5863 * @param alpha The opacity of the view.
Chet Haase73066682010-11-29 15:55:32 -08005864 *
Romain Guy171c5922011-01-06 10:04:23 -08005865 * @see #setLayerType(int, android.graphics.Paint)
5866 *
Chet Haase73066682010-11-29 15:55:32 -08005867 * @attr ref android.R.styleable#View_alpha
Chet Haasec3aa3612010-06-17 08:50:37 -07005868 */
5869 public void setAlpha(float alpha) {
5870 mAlpha = alpha;
Chet Haaseed032702010-10-01 14:05:54 -07005871 if (onSetAlpha((int) (alpha * 255))) {
Romain Guya3496a92010-10-12 11:53:24 -07005872 mPrivateFlags |= ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005873 // subclass is handling alpha - don't optimize rendering cache invalidation
5874 invalidate();
5875 } else {
Romain Guya3496a92010-10-12 11:53:24 -07005876 mPrivateFlags &= ~ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005877 invalidate(false);
5878 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005879 }
5880
5881 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005882 * Top position of this view relative to its parent.
5883 *
5884 * @return The top of this view, in pixels.
5885 */
5886 @ViewDebug.CapturedViewProperty
5887 public final int getTop() {
5888 return mTop;
5889 }
5890
5891 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005892 * Sets the top position of this view relative to its parent. This method is meant to be called
5893 * by the layout system and should not generally be called otherwise, because the property
5894 * may be changed at any time by the layout.
5895 *
5896 * @param top The top of this view, in pixels.
5897 */
5898 public final void setTop(int top) {
5899 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07005900 updateMatrix();
5901 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005902 final ViewParent p = mParent;
5903 if (p != null && mAttachInfo != null) {
5904 final Rect r = mAttachInfo.mTmpInvalRect;
5905 int minTop;
5906 int yLoc;
5907 if (top < mTop) {
5908 minTop = top;
5909 yLoc = top - mTop;
5910 } else {
5911 minTop = mTop;
5912 yLoc = 0;
5913 }
5914 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5915 p.invalidateChild(this, r);
5916 }
5917 } else {
5918 // Double-invalidation is necessary to capture view's old and new areas
5919 invalidate();
5920 }
5921
Chet Haaseed032702010-10-01 14:05:54 -07005922 int width = mRight - mLeft;
5923 int oldHeight = mBottom - mTop;
5924
Chet Haase21cd1382010-09-01 17:42:29 -07005925 mTop = top;
5926
Chet Haaseed032702010-10-01 14:05:54 -07005927 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5928
Chet Haase21cd1382010-09-01 17:42:29 -07005929 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005930 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5931 // A change in dimension means an auto-centered pivot point changes, too
5932 mMatrixDirty = true;
5933 }
Chet Haase21cd1382010-09-01 17:42:29 -07005934 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5935 invalidate();
5936 }
Chet Haase55dbb652010-12-21 20:15:08 -08005937 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07005938 }
5939 }
5940
5941 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 * Bottom position of this view relative to its parent.
5943 *
5944 * @return The bottom of this view, in pixels.
5945 */
5946 @ViewDebug.CapturedViewProperty
5947 public final int getBottom() {
5948 return mBottom;
5949 }
5950
5951 /**
Michael Jurkadab559a2011-01-04 20:31:51 -08005952 * True if this view has changed since the last time being drawn.
5953 *
5954 * @return The dirty state of this view.
5955 */
5956 public boolean isDirty() {
5957 return (mPrivateFlags & DIRTY_MASK) != 0;
5958 }
5959
5960 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005961 * Sets the bottom position of this view relative to its parent. This method is meant to be
5962 * called by the layout system and should not generally be called otherwise, because the
5963 * property may be changed at any time by the layout.
5964 *
5965 * @param bottom The bottom of this view, in pixels.
5966 */
5967 public final void setBottom(int bottom) {
5968 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07005969 updateMatrix();
5970 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005971 final ViewParent p = mParent;
5972 if (p != null && mAttachInfo != null) {
5973 final Rect r = mAttachInfo.mTmpInvalRect;
5974 int maxBottom;
5975 if (bottom < mBottom) {
5976 maxBottom = mBottom;
5977 } else {
5978 maxBottom = bottom;
5979 }
5980 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5981 p.invalidateChild(this, r);
5982 }
5983 } else {
5984 // Double-invalidation is necessary to capture view's old and new areas
5985 invalidate();
5986 }
5987
Chet Haaseed032702010-10-01 14:05:54 -07005988 int width = mRight - mLeft;
5989 int oldHeight = mBottom - mTop;
5990
Chet Haase21cd1382010-09-01 17:42:29 -07005991 mBottom = bottom;
5992
Chet Haaseed032702010-10-01 14:05:54 -07005993 onSizeChanged(width, mBottom - mTop, width, oldHeight);
5994
Chet Haase21cd1382010-09-01 17:42:29 -07005995 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005996 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5997 // A change in dimension means an auto-centered pivot point changes, too
5998 mMatrixDirty = true;
5999 }
Chet Haase21cd1382010-09-01 17:42:29 -07006000 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6001 invalidate();
6002 }
Chet Haase55dbb652010-12-21 20:15:08 -08006003 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006004 }
6005 }
6006
6007 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 * Left position of this view relative to its parent.
6009 *
6010 * @return The left edge of this view, in pixels.
6011 */
6012 @ViewDebug.CapturedViewProperty
6013 public final int getLeft() {
6014 return mLeft;
6015 }
6016
6017 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006018 * Sets the left position of this view relative to its parent. This method is meant to be called
6019 * by the layout system and should not generally be called otherwise, because the property
6020 * may be changed at any time by the layout.
6021 *
6022 * @param left The bottom of this view, in pixels.
6023 */
6024 public final void setLeft(int left) {
6025 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07006026 updateMatrix();
6027 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006028 final ViewParent p = mParent;
6029 if (p != null && mAttachInfo != null) {
6030 final Rect r = mAttachInfo.mTmpInvalRect;
6031 int minLeft;
6032 int xLoc;
6033 if (left < mLeft) {
6034 minLeft = left;
6035 xLoc = left - mLeft;
6036 } else {
6037 minLeft = mLeft;
6038 xLoc = 0;
6039 }
6040 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
6041 p.invalidateChild(this, r);
6042 }
6043 } else {
6044 // Double-invalidation is necessary to capture view's old and new areas
6045 invalidate();
6046 }
6047
Chet Haaseed032702010-10-01 14:05:54 -07006048 int oldWidth = mRight - mLeft;
6049 int height = mBottom - mTop;
6050
Chet Haase21cd1382010-09-01 17:42:29 -07006051 mLeft = left;
6052
Chet Haaseed032702010-10-01 14:05:54 -07006053 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6054
Chet Haase21cd1382010-09-01 17:42:29 -07006055 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006056 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6057 // A change in dimension means an auto-centered pivot point changes, too
6058 mMatrixDirty = true;
6059 }
Chet Haase21cd1382010-09-01 17:42:29 -07006060 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6061 invalidate();
6062 }
Chet Haase55dbb652010-12-21 20:15:08 -08006063 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006064 }
6065 }
6066
6067 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006068 * Right position of this view relative to its parent.
6069 *
6070 * @return The right edge of this view, in pixels.
6071 */
6072 @ViewDebug.CapturedViewProperty
6073 public final int getRight() {
6074 return mRight;
6075 }
6076
6077 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006078 * Sets the right position of this view relative to its parent. This method is meant to be called
6079 * by the layout system and should not generally be called otherwise, because the property
6080 * may be changed at any time by the layout.
6081 *
6082 * @param right The bottom of this view, in pixels.
6083 */
6084 public final void setRight(int right) {
6085 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07006086 updateMatrix();
6087 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006088 final ViewParent p = mParent;
6089 if (p != null && mAttachInfo != null) {
6090 final Rect r = mAttachInfo.mTmpInvalRect;
6091 int maxRight;
6092 if (right < mRight) {
6093 maxRight = mRight;
6094 } else {
6095 maxRight = right;
6096 }
6097 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
6098 p.invalidateChild(this, r);
6099 }
6100 } else {
6101 // Double-invalidation is necessary to capture view's old and new areas
6102 invalidate();
6103 }
6104
Chet Haaseed032702010-10-01 14:05:54 -07006105 int oldWidth = mRight - mLeft;
6106 int height = mBottom - mTop;
6107
Chet Haase21cd1382010-09-01 17:42:29 -07006108 mRight = right;
6109
Chet Haaseed032702010-10-01 14:05:54 -07006110 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6111
Chet Haase21cd1382010-09-01 17:42:29 -07006112 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006113 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6114 // A change in dimension means an auto-centered pivot point changes, too
6115 mMatrixDirty = true;
6116 }
Chet Haase21cd1382010-09-01 17:42:29 -07006117 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6118 invalidate();
6119 }
Chet Haase55dbb652010-12-21 20:15:08 -08006120 mBackgroundSizeChanged = true;
Chet Haase21cd1382010-09-01 17:42:29 -07006121 }
6122 }
6123
6124 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006125 * The visual x position of this view, in pixels. This is equivalent to the
6126 * {@link #setTranslationX(float) translationX} property plus the current
6127 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07006128 *
Chet Haasedf030d22010-07-30 17:22:38 -07006129 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006130 */
Chet Haasedf030d22010-07-30 17:22:38 -07006131 public float getX() {
6132 return mLeft + mTranslationX;
6133 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006134
Chet Haasedf030d22010-07-30 17:22:38 -07006135 /**
6136 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
6137 * {@link #setTranslationX(float) translationX} property to be the difference between
6138 * the x value passed in and the current {@link #getLeft() left} property.
6139 *
6140 * @param x The visual x position of this view, in pixels.
6141 */
6142 public void setX(float x) {
6143 setTranslationX(x - mLeft);
6144 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006145
Chet Haasedf030d22010-07-30 17:22:38 -07006146 /**
6147 * The visual y position of this view, in pixels. This is equivalent to the
6148 * {@link #setTranslationY(float) translationY} property plus the current
6149 * {@link #getTop() top} property.
6150 *
6151 * @return The visual y position of this view, in pixels.
6152 */
6153 public float getY() {
6154 return mTop + mTranslationY;
6155 }
6156
6157 /**
6158 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
6159 * {@link #setTranslationY(float) translationY} property to be the difference between
6160 * the y value passed in and the current {@link #getTop() top} property.
6161 *
6162 * @param y The visual y position of this view, in pixels.
6163 */
6164 public void setY(float y) {
6165 setTranslationY(y - mTop);
6166 }
6167
6168
6169 /**
6170 * The horizontal location of this view relative to its {@link #getLeft() left} position.
6171 * This position is post-layout, in addition to wherever the object's
6172 * layout placed it.
6173 *
6174 * @return The horizontal position of this view relative to its left position, in pixels.
6175 */
6176 public float getTranslationX() {
6177 return mTranslationX;
6178 }
6179
6180 /**
6181 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
6182 * This effectively positions the object post-layout, in addition to wherever the object's
6183 * layout placed it.
6184 *
6185 * @param translationX The horizontal position of this view relative to its left position,
6186 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006187 *
6188 * @attr ref android.R.styleable#View_translationX
Chet Haasedf030d22010-07-30 17:22:38 -07006189 */
6190 public void setTranslationX(float translationX) {
6191 if (mTranslationX != translationX) {
6192 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006193 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006194 mTranslationX = translationX;
6195 mMatrixDirty = true;
6196 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006197 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006198 }
6199 }
6200
6201 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006202 * The horizontal location of this view relative to its {@link #getTop() top} position.
6203 * This position is post-layout, in addition to wherever the object's
6204 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006205 *
Chet Haasedf030d22010-07-30 17:22:38 -07006206 * @return The vertical position of this view relative to its top position,
6207 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006208 */
Chet Haasedf030d22010-07-30 17:22:38 -07006209 public float getTranslationY() {
6210 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07006211 }
6212
6213 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006214 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
6215 * This effectively positions the object post-layout, in addition to wherever the object's
6216 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006217 *
Chet Haasedf030d22010-07-30 17:22:38 -07006218 * @param translationY The vertical position of this view relative to its top position,
6219 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006220 *
6221 * @attr ref android.R.styleable#View_translationY
Chet Haasec3aa3612010-06-17 08:50:37 -07006222 */
Chet Haasedf030d22010-07-30 17:22:38 -07006223 public void setTranslationY(float translationY) {
6224 if (mTranslationY != translationY) {
6225 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006226 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006227 mTranslationY = translationY;
6228 mMatrixDirty = true;
6229 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006230 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006231 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006232 }
6233
6234 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 * Hit rectangle in parent's coordinates
6236 *
6237 * @param outRect The hit rectangle of the view.
6238 */
6239 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07006240 updateMatrix();
6241 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006242 outRect.set(mLeft, mTop, mRight, mBottom);
6243 } else {
6244 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07006245 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07006246 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07006247 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
6248 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07006249 }
6250 }
6251
6252 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07006253 * Determines whether the given point, in local coordinates is inside the view.
6254 */
6255 /*package*/ final boolean pointInView(float localX, float localY) {
6256 return localX >= 0 && localX < (mRight - mLeft)
6257 && localY >= 0 && localY < (mBottom - mTop);
6258 }
6259
6260 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07006261 * Utility method to determine whether the given point, in local coordinates,
6262 * is inside the view, where the area of the view is expanded by the slop factor.
6263 * This method is called while processing touch-move events to determine if the event
6264 * is still within the view.
6265 */
6266 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07006267 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07006268 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 }
6270
6271 /**
6272 * When a view has focus and the user navigates away from it, the next view is searched for
6273 * starting from the rectangle filled in by this method.
6274 *
6275 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
6276 * view maintains some idea of internal selection, such as a cursor, or a selected row
6277 * or column, you should override this method and fill in a more specific rectangle.
6278 *
6279 * @param r The rectangle to fill in, in this view's coordinates.
6280 */
6281 public void getFocusedRect(Rect r) {
6282 getDrawingRect(r);
6283 }
6284
6285 /**
6286 * If some part of this view is not clipped by any of its parents, then
6287 * return that area in r in global (root) coordinates. To convert r to local
6288 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
6289 * -globalOffset.y)) If the view is completely clipped or translated out,
6290 * return false.
6291 *
6292 * @param r If true is returned, r holds the global coordinates of the
6293 * visible portion of this view.
6294 * @param globalOffset If true is returned, globalOffset holds the dx,dy
6295 * between this view and its root. globalOffet may be null.
6296 * @return true if r is non-empty (i.e. part of the view is visible at the
6297 * root level.
6298 */
6299 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
6300 int width = mRight - mLeft;
6301 int height = mBottom - mTop;
6302 if (width > 0 && height > 0) {
6303 r.set(0, 0, width, height);
6304 if (globalOffset != null) {
6305 globalOffset.set(-mScrollX, -mScrollY);
6306 }
6307 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
6308 }
6309 return false;
6310 }
6311
6312 public final boolean getGlobalVisibleRect(Rect r) {
6313 return getGlobalVisibleRect(r, null);
6314 }
6315
6316 public final boolean getLocalVisibleRect(Rect r) {
6317 Point offset = new Point();
6318 if (getGlobalVisibleRect(r, offset)) {
6319 r.offset(-offset.x, -offset.y); // make r local
6320 return true;
6321 }
6322 return false;
6323 }
6324
6325 /**
6326 * Offset this view's vertical location by the specified number of pixels.
6327 *
6328 * @param offset the number of pixels to offset the view by
6329 */
6330 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006331 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006332 updateMatrix();
6333 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006334 final ViewParent p = mParent;
6335 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006336 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006337 int minTop;
6338 int maxBottom;
6339 int yLoc;
6340 if (offset < 0) {
6341 minTop = mTop + offset;
6342 maxBottom = mBottom;
6343 yLoc = offset;
6344 } else {
6345 minTop = mTop;
6346 maxBottom = mBottom + offset;
6347 yLoc = 0;
6348 }
6349 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
6350 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006351 }
6352 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006353 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006354 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006355
Chet Haasec3aa3612010-06-17 08:50:37 -07006356 mTop += offset;
6357 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006358
Chet Haasec3aa3612010-06-17 08:50:37 -07006359 if (!mMatrixIsIdentity) {
6360 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006361 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006362 }
6363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006364 }
6365
6366 /**
6367 * Offset this view's horizontal location by the specified amount of pixels.
6368 *
6369 * @param offset the numer of pixels to offset the view by
6370 */
6371 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006372 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006373 updateMatrix();
6374 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006375 final ViewParent p = mParent;
6376 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006377 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006378 int minLeft;
6379 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006380 if (offset < 0) {
6381 minLeft = mLeft + offset;
6382 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006383 } else {
6384 minLeft = mLeft;
6385 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006386 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006387 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07006388 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006389 }
6390 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006391 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006392 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006393
Chet Haasec3aa3612010-06-17 08:50:37 -07006394 mLeft += offset;
6395 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006396
Chet Haasec3aa3612010-06-17 08:50:37 -07006397 if (!mMatrixIsIdentity) {
6398 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006399 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006400 }
6401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 }
6403
6404 /**
6405 * Get the LayoutParams associated with this view. All views should have
6406 * layout parameters. These supply parameters to the <i>parent</i> of this
6407 * view specifying how it should be arranged. There are many subclasses of
6408 * ViewGroup.LayoutParams, and these correspond to the different subclasses
6409 * of ViewGroup that are responsible for arranging their children.
6410 * @return The LayoutParams associated with this view
6411 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07006412 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 public ViewGroup.LayoutParams getLayoutParams() {
6414 return mLayoutParams;
6415 }
6416
6417 /**
6418 * Set the layout parameters associated with this view. These supply
6419 * parameters to the <i>parent</i> of this view specifying how it should be
6420 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6421 * correspond to the different subclasses of ViewGroup that are responsible
6422 * for arranging their children.
6423 *
6424 * @param params the layout parameters for this view
6425 */
6426 public void setLayoutParams(ViewGroup.LayoutParams params) {
6427 if (params == null) {
6428 throw new NullPointerException("params == null");
6429 }
6430 mLayoutParams = params;
6431 requestLayout();
6432 }
6433
6434 /**
6435 * Set the scrolled position of your view. This will cause a call to
6436 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6437 * invalidated.
6438 * @param x the x position to scroll to
6439 * @param y the y position to scroll to
6440 */
6441 public void scrollTo(int x, int y) {
6442 if (mScrollX != x || mScrollY != y) {
6443 int oldX = mScrollX;
6444 int oldY = mScrollY;
6445 mScrollX = x;
6446 mScrollY = y;
6447 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006448 if (!awakenScrollBars()) {
6449 invalidate();
6450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 }
6452 }
6453
6454 /**
6455 * Move the scrolled position of your view. This will cause a call to
6456 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6457 * invalidated.
6458 * @param x the amount of pixels to scroll by horizontally
6459 * @param y the amount of pixels to scroll by vertically
6460 */
6461 public void scrollBy(int x, int y) {
6462 scrollTo(mScrollX + x, mScrollY + y);
6463 }
6464
6465 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006466 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6467 * animation to fade the scrollbars out after a default delay. If a subclass
6468 * provides animated scrolling, the start delay should equal the duration
6469 * of the scrolling animation.</p>
6470 *
6471 * <p>The animation starts only if at least one of the scrollbars is
6472 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6473 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6474 * this method returns true, and false otherwise. If the animation is
6475 * started, this method calls {@link #invalidate()}; in that case the
6476 * caller should not call {@link #invalidate()}.</p>
6477 *
6478 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006479 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006480 *
6481 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6482 * and {@link #scrollTo(int, int)}.</p>
6483 *
6484 * @return true if the animation is played, false otherwise
6485 *
6486 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006487 * @see #scrollBy(int, int)
6488 * @see #scrollTo(int, int)
6489 * @see #isHorizontalScrollBarEnabled()
6490 * @see #isVerticalScrollBarEnabled()
6491 * @see #setHorizontalScrollBarEnabled(boolean)
6492 * @see #setVerticalScrollBarEnabled(boolean)
6493 */
6494 protected boolean awakenScrollBars() {
6495 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006496 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006497 }
6498
6499 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006500 * Trigger the scrollbars to draw.
6501 * This method differs from awakenScrollBars() only in its default duration.
6502 * initialAwakenScrollBars() will show the scroll bars for longer than
6503 * usual to give the user more of a chance to notice them.
6504 *
6505 * @return true if the animation is played, false otherwise.
6506 */
6507 private boolean initialAwakenScrollBars() {
6508 return mScrollCache != null &&
6509 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6510 }
6511
6512 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006513 * <p>
6514 * Trigger the scrollbars to draw. When invoked this method starts an
6515 * animation to fade the scrollbars out after a fixed delay. If a subclass
6516 * provides animated scrolling, the start delay should equal the duration of
6517 * the scrolling animation.
6518 * </p>
6519 *
6520 * <p>
6521 * The animation starts only if at least one of the scrollbars is enabled,
6522 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6523 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6524 * this method returns true, and false otherwise. If the animation is
6525 * started, this method calls {@link #invalidate()}; in that case the caller
6526 * should not call {@link #invalidate()}.
6527 * </p>
6528 *
6529 * <p>
6530 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006531 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006532 * </p>
6533 *
6534 * @param startDelay the delay, in milliseconds, after which the animation
6535 * should start; when the delay is 0, the animation starts
6536 * immediately
6537 * @return true if the animation is played, false otherwise
6538 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006539 * @see #scrollBy(int, int)
6540 * @see #scrollTo(int, int)
6541 * @see #isHorizontalScrollBarEnabled()
6542 * @see #isVerticalScrollBarEnabled()
6543 * @see #setHorizontalScrollBarEnabled(boolean)
6544 * @see #setVerticalScrollBarEnabled(boolean)
6545 */
6546 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006547 return awakenScrollBars(startDelay, true);
6548 }
6549
6550 /**
6551 * <p>
6552 * Trigger the scrollbars to draw. When invoked this method starts an
6553 * animation to fade the scrollbars out after a fixed delay. If a subclass
6554 * provides animated scrolling, the start delay should equal the duration of
6555 * the scrolling animation.
6556 * </p>
6557 *
6558 * <p>
6559 * The animation starts only if at least one of the scrollbars is enabled,
6560 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6561 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6562 * this method returns true, and false otherwise. If the animation is
6563 * started, this method calls {@link #invalidate()} if the invalidate parameter
6564 * is set to true; in that case the caller
6565 * should not call {@link #invalidate()}.
6566 * </p>
6567 *
6568 * <p>
6569 * This method should be invoked everytime a subclass directly updates the
6570 * scroll parameters.
6571 * </p>
6572 *
6573 * @param startDelay the delay, in milliseconds, after which the animation
6574 * should start; when the delay is 0, the animation starts
6575 * immediately
6576 *
6577 * @param invalidate Wheter this method should call invalidate
6578 *
6579 * @return true if the animation is played, false otherwise
6580 *
6581 * @see #scrollBy(int, int)
6582 * @see #scrollTo(int, int)
6583 * @see #isHorizontalScrollBarEnabled()
6584 * @see #isVerticalScrollBarEnabled()
6585 * @see #setHorizontalScrollBarEnabled(boolean)
6586 * @see #setVerticalScrollBarEnabled(boolean)
6587 */
6588 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006589 final ScrollabilityCache scrollCache = mScrollCache;
6590
6591 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6592 return false;
6593 }
6594
6595 if (scrollCache.scrollBar == null) {
6596 scrollCache.scrollBar = new ScrollBarDrawable();
6597 }
6598
6599 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6600
Mike Cleron290947b2009-09-29 18:34:32 -07006601 if (invalidate) {
6602 // Invalidate to show the scrollbars
6603 invalidate();
6604 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006605
6606 if (scrollCache.state == ScrollabilityCache.OFF) {
6607 // FIXME: this is copied from WindowManagerService.
6608 // We should get this value from the system when it
6609 // is possible to do so.
6610 final int KEY_REPEAT_FIRST_DELAY = 750;
6611 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6612 }
6613
6614 // Tell mScrollCache when we should start fading. This may
6615 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006616 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006617 scrollCache.fadeStartTime = fadeStartTime;
6618 scrollCache.state = ScrollabilityCache.ON;
6619
6620 // Schedule our fader to run, unscheduling any old ones first
6621 if (mAttachInfo != null) {
6622 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6623 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6624 }
6625
6626 return true;
6627 }
6628
6629 return false;
6630 }
6631
6632 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 * Mark the the area defined by dirty as needing to be drawn. If the view is
6634 * visible, {@link #onDraw} will be called at some point in the future.
6635 * This must be called from a UI thread. To call from a non-UI thread, call
6636 * {@link #postInvalidate()}.
6637 *
6638 * WARNING: This method is destructive to dirty.
6639 * @param dirty the rectangle representing the bounds of the dirty region
6640 */
6641 public void invalidate(Rect dirty) {
6642 if (ViewDebug.TRACE_HIERARCHY) {
6643 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6644 }
6645
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006646 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6647 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6649 final ViewParent p = mParent;
6650 final AttachInfo ai = mAttachInfo;
Romain Guyaf636eb2010-12-09 17:47:21 -08006651 if (p != null && ai != null && ai.mHardwareAccelerated) {
6652 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6653 // with a null dirty rect, which tells the ViewRoot to redraw everything
6654 p.invalidateChild(this, null);
6655 return;
6656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006657 if (p != null && ai != null) {
6658 final int scrollX = mScrollX;
6659 final int scrollY = mScrollY;
6660 final Rect r = ai.mTmpInvalRect;
6661 r.set(dirty.left - scrollX, dirty.top - scrollY,
6662 dirty.right - scrollX, dirty.bottom - scrollY);
6663 mParent.invalidateChild(this, r);
6664 }
6665 }
6666 }
6667
6668 /**
6669 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6670 * The coordinates of the dirty rect are relative to the view.
6671 * If the view is visible, {@link #onDraw} will be called at some point
6672 * in the future. This must be called from a UI thread. To call
6673 * from a non-UI thread, call {@link #postInvalidate()}.
6674 * @param l the left position of the dirty region
6675 * @param t the top position of the dirty region
6676 * @param r the right position of the dirty region
6677 * @param b the bottom position of the dirty region
6678 */
6679 public void invalidate(int l, int t, int r, int b) {
6680 if (ViewDebug.TRACE_HIERARCHY) {
6681 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6682 }
6683
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006684 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6685 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006686 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6687 final ViewParent p = mParent;
6688 final AttachInfo ai = mAttachInfo;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006689 if (p != null && ai != null && ai.mHardwareAccelerated) {
6690 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6691 // with a null dirty rect, which tells the ViewRoot to redraw everything
6692 p.invalidateChild(this, null);
6693 return;
6694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 if (p != null && ai != null && l < r && t < b) {
6696 final int scrollX = mScrollX;
6697 final int scrollY = mScrollY;
6698 final Rect tmpr = ai.mTmpInvalRect;
6699 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6700 p.invalidateChild(this, tmpr);
6701 }
6702 }
6703 }
6704
6705 /**
6706 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6707 * be called at some point in the future. This must be called from a
6708 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6709 */
6710 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006711 invalidate(true);
6712 }
6713
6714 /**
6715 * This is where the invalidate() work actually happens. A full invalidate()
6716 * causes the drawing cache to be invalidated, but this function can be called with
6717 * invalidateCache set to false to skip that invalidation step for cases that do not
6718 * need it (for example, a component that remains at the same dimensions with the same
6719 * content).
6720 *
6721 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6722 * well. This is usually true for a full invalidate, but may be set to false if the
6723 * View's contents or dimensions have not changed.
6724 */
6725 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006726 if (ViewDebug.TRACE_HIERARCHY) {
6727 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6728 }
6729
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006730 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6731 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID)) {
Chet Haaseed032702010-10-01 14:05:54 -07006732 mPrivateFlags &= ~DRAWN;
6733 if (invalidateCache) {
6734 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 final AttachInfo ai = mAttachInfo;
Chet Haase70d4ba12010-10-06 09:46:45 -07006737 final ViewParent p = mParent;
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006738 if (p != null && ai != null && ai.mHardwareAccelerated) {
6739 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6740 // with a null dirty rect, which tells the ViewRoot to redraw everything
6741 p.invalidateChild(this, null);
6742 return;
6743 }
Michael Jurkaebefea42010-11-15 16:04:01 -08006744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 if (p != null && ai != null) {
6746 final Rect r = ai.mTmpInvalRect;
6747 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6748 // Don't call invalidate -- we don't want to internally scroll
6749 // our own bounds
6750 p.invalidateChild(this, r);
6751 }
6752 }
6753 }
6754
6755 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006756 * Indicates whether this View is opaque. An opaque View guarantees that it will
6757 * draw all the pixels overlapping its bounds using a fully opaque color.
6758 *
6759 * Subclasses of View should override this method whenever possible to indicate
6760 * whether an instance is opaque. Opaque Views are treated in a special way by
6761 * the View hierarchy, possibly allowing it to perform optimizations during
6762 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006763 *
Romain Guy24443ea2009-05-11 11:56:30 -07006764 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006765 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006766 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006767 public boolean isOpaque() {
Chet Haase70d4ba12010-10-06 09:46:45 -07006768 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6769 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
Romain Guy8f1344f52009-05-15 16:03:59 -07006770 }
6771
Adam Powell20232d02010-12-08 21:08:53 -08006772 /**
6773 * @hide
6774 */
6775 protected void computeOpaqueFlags() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006776 // Opaque if:
6777 // - Has a background
6778 // - Background is opaque
6779 // - Doesn't have scrollbars or scrollbars are inside overlay
6780
6781 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6782 mPrivateFlags |= OPAQUE_BACKGROUND;
6783 } else {
6784 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6785 }
6786
6787 final int flags = mViewFlags;
6788 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6789 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6790 mPrivateFlags |= OPAQUE_SCROLLBARS;
6791 } else {
6792 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6793 }
6794 }
6795
6796 /**
6797 * @hide
6798 */
6799 protected boolean hasOpaqueScrollbars() {
6800 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006801 }
6802
6803 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006804 * @return A handler associated with the thread running the View. This
6805 * handler can be used to pump events in the UI events queue.
6806 */
6807 public Handler getHandler() {
6808 if (mAttachInfo != null) {
6809 return mAttachInfo.mHandler;
6810 }
6811 return null;
6812 }
6813
6814 /**
6815 * Causes the Runnable to be added to the message queue.
6816 * The runnable will be run on the user interface thread.
6817 *
6818 * @param action The Runnable that will be executed.
6819 *
6820 * @return Returns true if the Runnable was successfully placed in to the
6821 * message queue. Returns false on failure, usually because the
6822 * looper processing the message queue is exiting.
6823 */
6824 public boolean post(Runnable action) {
6825 Handler handler;
6826 if (mAttachInfo != null) {
6827 handler = mAttachInfo.mHandler;
6828 } else {
6829 // Assume that post will succeed later
6830 ViewRoot.getRunQueue().post(action);
6831 return true;
6832 }
6833
6834 return handler.post(action);
6835 }
6836
6837 /**
6838 * Causes the Runnable to be added to the message queue, to be run
6839 * after the specified amount of time elapses.
6840 * The runnable will be run on the user interface thread.
6841 *
6842 * @param action The Runnable that will be executed.
6843 * @param delayMillis The delay (in milliseconds) until the Runnable
6844 * will be executed.
6845 *
6846 * @return true if the Runnable was successfully placed in to the
6847 * message queue. Returns false on failure, usually because the
6848 * looper processing the message queue is exiting. Note that a
6849 * result of true does not mean the Runnable will be processed --
6850 * if the looper is quit before the delivery time of the message
6851 * occurs then the message will be dropped.
6852 */
6853 public boolean postDelayed(Runnable action, long delayMillis) {
6854 Handler handler;
6855 if (mAttachInfo != null) {
6856 handler = mAttachInfo.mHandler;
6857 } else {
6858 // Assume that post will succeed later
6859 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6860 return true;
6861 }
6862
6863 return handler.postDelayed(action, delayMillis);
6864 }
6865
6866 /**
6867 * Removes the specified Runnable from the message queue.
6868 *
6869 * @param action The Runnable to remove from the message handling queue
6870 *
6871 * @return true if this view could ask the Handler to remove the Runnable,
6872 * false otherwise. When the returned value is true, the Runnable
6873 * may or may not have been actually removed from the message queue
6874 * (for instance, if the Runnable was not in the queue already.)
6875 */
6876 public boolean removeCallbacks(Runnable action) {
6877 Handler handler;
6878 if (mAttachInfo != null) {
6879 handler = mAttachInfo.mHandler;
6880 } else {
6881 // Assume that post will succeed later
6882 ViewRoot.getRunQueue().removeCallbacks(action);
6883 return true;
6884 }
6885
6886 handler.removeCallbacks(action);
6887 return true;
6888 }
6889
6890 /**
6891 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6892 * Use this to invalidate the View from a non-UI thread.
6893 *
6894 * @see #invalidate()
6895 */
6896 public void postInvalidate() {
6897 postInvalidateDelayed(0);
6898 }
6899
6900 /**
6901 * Cause an invalidate of the specified area to happen on a subsequent cycle
6902 * through the event loop. Use this to invalidate the View from a non-UI thread.
6903 *
6904 * @param left The left coordinate of the rectangle to invalidate.
6905 * @param top The top coordinate of the rectangle to invalidate.
6906 * @param right The right coordinate of the rectangle to invalidate.
6907 * @param bottom The bottom coordinate of the rectangle to invalidate.
6908 *
6909 * @see #invalidate(int, int, int, int)
6910 * @see #invalidate(Rect)
6911 */
6912 public void postInvalidate(int left, int top, int right, int bottom) {
6913 postInvalidateDelayed(0, left, top, right, bottom);
6914 }
6915
6916 /**
6917 * Cause an invalidate to happen on a subsequent cycle through the event
6918 * loop. Waits for the specified amount of time.
6919 *
6920 * @param delayMilliseconds the duration in milliseconds to delay the
6921 * invalidation by
6922 */
6923 public void postInvalidateDelayed(long delayMilliseconds) {
6924 // We try only with the AttachInfo because there's no point in invalidating
6925 // if we are not attached to our window
6926 if (mAttachInfo != null) {
6927 Message msg = Message.obtain();
6928 msg.what = AttachInfo.INVALIDATE_MSG;
6929 msg.obj = this;
6930 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6931 }
6932 }
6933
6934 /**
6935 * Cause an invalidate of the specified area to happen on a subsequent cycle
6936 * through the event loop. Waits for the specified amount of time.
6937 *
6938 * @param delayMilliseconds the duration in milliseconds to delay the
6939 * invalidation by
6940 * @param left The left coordinate of the rectangle to invalidate.
6941 * @param top The top coordinate of the rectangle to invalidate.
6942 * @param right The right coordinate of the rectangle to invalidate.
6943 * @param bottom The bottom coordinate of the rectangle to invalidate.
6944 */
6945 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6946 int right, int bottom) {
6947
6948 // We try only with the AttachInfo because there's no point in invalidating
6949 // if we are not attached to our window
6950 if (mAttachInfo != null) {
6951 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6952 info.target = this;
6953 info.left = left;
6954 info.top = top;
6955 info.right = right;
6956 info.bottom = bottom;
6957
6958 final Message msg = Message.obtain();
6959 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6960 msg.obj = info;
6961 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6962 }
6963 }
6964
6965 /**
6966 * Called by a parent to request that a child update its values for mScrollX
6967 * and mScrollY if necessary. This will typically be done if the child is
6968 * animating a scroll using a {@link android.widget.Scroller Scroller}
6969 * object.
6970 */
6971 public void computeScroll() {
6972 }
6973
6974 /**
6975 * <p>Indicate whether the horizontal edges are faded when the view is
6976 * scrolled horizontally.</p>
6977 *
6978 * @return true if the horizontal edges should are faded on scroll, false
6979 * otherwise
6980 *
6981 * @see #setHorizontalFadingEdgeEnabled(boolean)
6982 * @attr ref android.R.styleable#View_fadingEdge
6983 */
6984 public boolean isHorizontalFadingEdgeEnabled() {
6985 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6986 }
6987
6988 /**
6989 * <p>Define whether the horizontal edges should be faded when this view
6990 * is scrolled horizontally.</p>
6991 *
6992 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6993 * be faded when the view is scrolled
6994 * horizontally
6995 *
6996 * @see #isHorizontalFadingEdgeEnabled()
6997 * @attr ref android.R.styleable#View_fadingEdge
6998 */
6999 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
7000 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
7001 if (horizontalFadingEdgeEnabled) {
7002 initScrollCache();
7003 }
7004
7005 mViewFlags ^= FADING_EDGE_HORIZONTAL;
7006 }
7007 }
7008
7009 /**
7010 * <p>Indicate whether the vertical edges are faded when the view is
7011 * scrolled horizontally.</p>
7012 *
7013 * @return true if the vertical edges should are faded on scroll, false
7014 * otherwise
7015 *
7016 * @see #setVerticalFadingEdgeEnabled(boolean)
7017 * @attr ref android.R.styleable#View_fadingEdge
7018 */
7019 public boolean isVerticalFadingEdgeEnabled() {
7020 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
7021 }
7022
7023 /**
7024 * <p>Define whether the vertical edges should be faded when this view
7025 * is scrolled vertically.</p>
7026 *
7027 * @param verticalFadingEdgeEnabled true if the vertical edges should
7028 * be faded when the view is scrolled
7029 * vertically
7030 *
7031 * @see #isVerticalFadingEdgeEnabled()
7032 * @attr ref android.R.styleable#View_fadingEdge
7033 */
7034 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
7035 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
7036 if (verticalFadingEdgeEnabled) {
7037 initScrollCache();
7038 }
7039
7040 mViewFlags ^= FADING_EDGE_VERTICAL;
7041 }
7042 }
7043
7044 /**
7045 * Returns the strength, or intensity, of the top faded edge. The strength is
7046 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7047 * returns 0.0 or 1.0 but no value in between.
7048 *
7049 * Subclasses should override this method to provide a smoother fade transition
7050 * when scrolling occurs.
7051 *
7052 * @return the intensity of the top fade as a float between 0.0f and 1.0f
7053 */
7054 protected float getTopFadingEdgeStrength() {
7055 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
7056 }
7057
7058 /**
7059 * Returns the strength, or intensity, of the bottom faded edge. The strength is
7060 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7061 * returns 0.0 or 1.0 but no value in between.
7062 *
7063 * Subclasses should override this method to provide a smoother fade transition
7064 * when scrolling occurs.
7065 *
7066 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
7067 */
7068 protected float getBottomFadingEdgeStrength() {
7069 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
7070 computeVerticalScrollRange() ? 1.0f : 0.0f;
7071 }
7072
7073 /**
7074 * Returns the strength, or intensity, of the left faded edge. The strength is
7075 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7076 * returns 0.0 or 1.0 but no value in between.
7077 *
7078 * Subclasses should override this method to provide a smoother fade transition
7079 * when scrolling occurs.
7080 *
7081 * @return the intensity of the left fade as a float between 0.0f and 1.0f
7082 */
7083 protected float getLeftFadingEdgeStrength() {
7084 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
7085 }
7086
7087 /**
7088 * Returns the strength, or intensity, of the right faded edge. The strength is
7089 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7090 * returns 0.0 or 1.0 but no value in between.
7091 *
7092 * Subclasses should override this method to provide a smoother fade transition
7093 * when scrolling occurs.
7094 *
7095 * @return the intensity of the right fade as a float between 0.0f and 1.0f
7096 */
7097 protected float getRightFadingEdgeStrength() {
7098 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
7099 computeHorizontalScrollRange() ? 1.0f : 0.0f;
7100 }
7101
7102 /**
7103 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
7104 * scrollbar is not drawn by default.</p>
7105 *
7106 * @return true if the horizontal scrollbar should be painted, false
7107 * otherwise
7108 *
7109 * @see #setHorizontalScrollBarEnabled(boolean)
7110 */
7111 public boolean isHorizontalScrollBarEnabled() {
7112 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7113 }
7114
7115 /**
7116 * <p>Define whether the horizontal scrollbar should be drawn or not. The
7117 * scrollbar is not drawn by default.</p>
7118 *
7119 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
7120 * be painted
7121 *
7122 * @see #isHorizontalScrollBarEnabled()
7123 */
7124 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
7125 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
7126 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007127 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007128 recomputePadding();
7129 }
7130 }
7131
7132 /**
7133 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
7134 * scrollbar is not drawn by default.</p>
7135 *
7136 * @return true if the vertical scrollbar should be painted, false
7137 * otherwise
7138 *
7139 * @see #setVerticalScrollBarEnabled(boolean)
7140 */
7141 public boolean isVerticalScrollBarEnabled() {
7142 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
7143 }
7144
7145 /**
7146 * <p>Define whether the vertical scrollbar should be drawn or not. The
7147 * scrollbar is not drawn by default.</p>
7148 *
7149 * @param verticalScrollBarEnabled true if the vertical scrollbar should
7150 * be painted
7151 *
7152 * @see #isVerticalScrollBarEnabled()
7153 */
7154 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
7155 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
7156 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007157 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007158 recomputePadding();
7159 }
7160 }
7161
Adam Powell20232d02010-12-08 21:08:53 -08007162 /**
7163 * @hide
7164 */
7165 protected void recomputePadding() {
7166 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007167 }
Mike Cleronfe81d382009-09-28 14:22:16 -07007168
7169 /**
7170 * Define whether scrollbars will fade when the view is not scrolling.
7171 *
7172 * @param fadeScrollbars wheter to enable fading
7173 *
7174 */
7175 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
7176 initScrollCache();
7177 final ScrollabilityCache scrollabilityCache = mScrollCache;
7178 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07007179 if (fadeScrollbars) {
7180 scrollabilityCache.state = ScrollabilityCache.OFF;
7181 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07007182 scrollabilityCache.state = ScrollabilityCache.ON;
7183 }
7184 }
7185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007186 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07007187 *
7188 * Returns true if scrollbars will fade when this view is not scrolling
7189 *
7190 * @return true if scrollbar fading is enabled
7191 */
7192 public boolean isScrollbarFadingEnabled() {
7193 return mScrollCache != null && mScrollCache.fadeScrollBars;
7194 }
7195
7196 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
7198 * inset. When inset, they add to the padding of the view. And the scrollbars
7199 * can be drawn inside the padding area or on the edge of the view. For example,
7200 * if a view has a background drawable and you want to draw the scrollbars
7201 * inside the padding specified by the drawable, you can use
7202 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
7203 * appear at the edge of the view, ignoring the padding, then you can use
7204 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
7205 * @param style the style of the scrollbars. Should be one of
7206 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
7207 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
7208 * @see #SCROLLBARS_INSIDE_OVERLAY
7209 * @see #SCROLLBARS_INSIDE_INSET
7210 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7211 * @see #SCROLLBARS_OUTSIDE_INSET
7212 */
7213 public void setScrollBarStyle(int style) {
7214 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
7215 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07007216 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007217 recomputePadding();
7218 }
7219 }
7220
7221 /**
7222 * <p>Returns the current scrollbar style.</p>
7223 * @return the current scrollbar style
7224 * @see #SCROLLBARS_INSIDE_OVERLAY
7225 * @see #SCROLLBARS_INSIDE_INSET
7226 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7227 * @see #SCROLLBARS_OUTSIDE_INSET
7228 */
7229 public int getScrollBarStyle() {
7230 return mViewFlags & SCROLLBARS_STYLE_MASK;
7231 }
7232
7233 /**
7234 * <p>Compute the horizontal range that the horizontal scrollbar
7235 * represents.</p>
7236 *
7237 * <p>The range is expressed in arbitrary units that must be the same as the
7238 * units used by {@link #computeHorizontalScrollExtent()} and
7239 * {@link #computeHorizontalScrollOffset()}.</p>
7240 *
7241 * <p>The default range is the drawing width of this view.</p>
7242 *
7243 * @return the total horizontal range represented by the horizontal
7244 * scrollbar
7245 *
7246 * @see #computeHorizontalScrollExtent()
7247 * @see #computeHorizontalScrollOffset()
7248 * @see android.widget.ScrollBarDrawable
7249 */
7250 protected int computeHorizontalScrollRange() {
7251 return getWidth();
7252 }
7253
7254 /**
7255 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
7256 * within the horizontal range. This value is used to compute the position
7257 * of the thumb within the scrollbar's track.</p>
7258 *
7259 * <p>The range is expressed in arbitrary units that must be the same as the
7260 * units used by {@link #computeHorizontalScrollRange()} and
7261 * {@link #computeHorizontalScrollExtent()}.</p>
7262 *
7263 * <p>The default offset is the scroll offset of this view.</p>
7264 *
7265 * @return the horizontal offset of the scrollbar's thumb
7266 *
7267 * @see #computeHorizontalScrollRange()
7268 * @see #computeHorizontalScrollExtent()
7269 * @see android.widget.ScrollBarDrawable
7270 */
7271 protected int computeHorizontalScrollOffset() {
7272 return mScrollX;
7273 }
7274
7275 /**
7276 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
7277 * within the horizontal range. This value is used to compute the length
7278 * of the thumb within the scrollbar's track.</p>
7279 *
7280 * <p>The range is expressed in arbitrary units that must be the same as the
7281 * units used by {@link #computeHorizontalScrollRange()} and
7282 * {@link #computeHorizontalScrollOffset()}.</p>
7283 *
7284 * <p>The default extent is the drawing width of this view.</p>
7285 *
7286 * @return the horizontal extent of the scrollbar's thumb
7287 *
7288 * @see #computeHorizontalScrollRange()
7289 * @see #computeHorizontalScrollOffset()
7290 * @see android.widget.ScrollBarDrawable
7291 */
7292 protected int computeHorizontalScrollExtent() {
7293 return getWidth();
7294 }
7295
7296 /**
7297 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
7298 *
7299 * <p>The range is expressed in arbitrary units that must be the same as the
7300 * units used by {@link #computeVerticalScrollExtent()} and
7301 * {@link #computeVerticalScrollOffset()}.</p>
7302 *
7303 * @return the total vertical range represented by the vertical scrollbar
7304 *
7305 * <p>The default range is the drawing height of this view.</p>
7306 *
7307 * @see #computeVerticalScrollExtent()
7308 * @see #computeVerticalScrollOffset()
7309 * @see android.widget.ScrollBarDrawable
7310 */
7311 protected int computeVerticalScrollRange() {
7312 return getHeight();
7313 }
7314
7315 /**
7316 * <p>Compute the vertical offset of the vertical scrollbar's thumb
7317 * within the horizontal range. This value is used to compute the position
7318 * of the thumb within the scrollbar's track.</p>
7319 *
7320 * <p>The range is expressed in arbitrary units that must be the same as the
7321 * units used by {@link #computeVerticalScrollRange()} and
7322 * {@link #computeVerticalScrollExtent()}.</p>
7323 *
7324 * <p>The default offset is the scroll offset of this view.</p>
7325 *
7326 * @return the vertical offset of the scrollbar's thumb
7327 *
7328 * @see #computeVerticalScrollRange()
7329 * @see #computeVerticalScrollExtent()
7330 * @see android.widget.ScrollBarDrawable
7331 */
7332 protected int computeVerticalScrollOffset() {
7333 return mScrollY;
7334 }
7335
7336 /**
7337 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7338 * within the vertical range. This value is used to compute the length
7339 * of the thumb within the scrollbar's track.</p>
7340 *
7341 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08007342 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007343 * {@link #computeVerticalScrollOffset()}.</p>
7344 *
7345 * <p>The default extent is the drawing height of this view.</p>
7346 *
7347 * @return the vertical extent of the scrollbar's thumb
7348 *
7349 * @see #computeVerticalScrollRange()
7350 * @see #computeVerticalScrollOffset()
7351 * @see android.widget.ScrollBarDrawable
7352 */
7353 protected int computeVerticalScrollExtent() {
7354 return getHeight();
7355 }
7356
7357 /**
7358 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7359 * scrollbars are painted only if they have been awakened first.</p>
7360 *
7361 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07007362 *
7363 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007364 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08007365 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007366 // scrollbars are drawn only when the animation is running
7367 final ScrollabilityCache cache = mScrollCache;
7368 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007369
7370 int state = cache.state;
7371
7372 if (state == ScrollabilityCache.OFF) {
7373 return;
7374 }
7375
7376 boolean invalidate = false;
7377
7378 if (state == ScrollabilityCache.FADING) {
7379 // We're fading -- get our fade interpolation
7380 if (cache.interpolatorValues == null) {
7381 cache.interpolatorValues = new float[1];
7382 }
7383
7384 float[] values = cache.interpolatorValues;
7385
7386 // Stops the animation if we're done
7387 if (cache.scrollBarInterpolator.timeToValues(values) ==
7388 Interpolator.Result.FREEZE_END) {
7389 cache.state = ScrollabilityCache.OFF;
7390 } else {
7391 cache.scrollBar.setAlpha(Math.round(values[0]));
7392 }
7393
7394 // This will make the scroll bars inval themselves after
7395 // drawing. We only want this when we're fading so that
7396 // we prevent excessive redraws
7397 invalidate = true;
7398 } else {
7399 // We're just on -- but we may have been fading before so
7400 // reset alpha
7401 cache.scrollBar.setAlpha(255);
7402 }
7403
7404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007405 final int viewFlags = mViewFlags;
7406
7407 final boolean drawHorizontalScrollBar =
7408 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7409 final boolean drawVerticalScrollBar =
7410 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7411 && !isVerticalScrollBarHidden();
7412
7413 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7414 final int width = mRight - mLeft;
7415 final int height = mBottom - mTop;
7416
7417 final ScrollBarDrawable scrollBar = cache.scrollBar;
7418 int size = scrollBar.getSize(false);
7419 if (size <= 0) {
7420 size = cache.scrollBarSize;
7421 }
7422
Mike Reede8853fc2009-09-04 14:01:48 -04007423 final int scrollX = mScrollX;
7424 final int scrollY = mScrollY;
7425 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7426
Mike Cleronf116bf82009-09-27 19:14:12 -07007427 int left, top, right, bottom;
7428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007429 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007430 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04007431 computeHorizontalScrollOffset(),
7432 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04007433 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07007434 getVerticalScrollbarWidth() : 0;
7435 top = scrollY + height - size - (mUserPaddingBottom & inside);
7436 left = scrollX + (mPaddingLeft & inside);
7437 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7438 bottom = top + size;
7439 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7440 if (invalidate) {
7441 invalidate(left, top, right, bottom);
7442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007443 }
7444
7445 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04007446 scrollBar.setParameters(computeVerticalScrollRange(),
7447 computeVerticalScrollOffset(),
7448 computeVerticalScrollExtent(), true);
Adam Powell20232d02010-12-08 21:08:53 -08007449 switch (mVerticalScrollbarPosition) {
7450 default:
7451 case SCROLLBAR_POSITION_DEFAULT:
7452 case SCROLLBAR_POSITION_RIGHT:
7453 left = scrollX + width - size - (mUserPaddingRight & inside);
7454 break;
7455 case SCROLLBAR_POSITION_LEFT:
7456 left = scrollX + (mUserPaddingLeft & inside);
7457 break;
7458 }
Mike Cleronf116bf82009-09-27 19:14:12 -07007459 top = scrollY + (mPaddingTop & inside);
7460 right = left + size;
7461 bottom = scrollY + height - (mUserPaddingBottom & inside);
7462 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7463 if (invalidate) {
7464 invalidate(left, top, right, bottom);
7465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007466 }
7467 }
7468 }
7469 }
Romain Guy8506ab42009-06-11 17:35:47 -07007470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007471 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007472 * 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 -08007473 * FastScroller is visible.
7474 * @return whether to temporarily hide the vertical scrollbar
7475 * @hide
7476 */
7477 protected boolean isVerticalScrollBarHidden() {
7478 return false;
7479 }
7480
7481 /**
7482 * <p>Draw the horizontal scrollbar if
7483 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7484 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007485 * @param canvas the canvas on which to draw the scrollbar
7486 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007487 *
7488 * @see #isHorizontalScrollBarEnabled()
7489 * @see #computeHorizontalScrollRange()
7490 * @see #computeHorizontalScrollExtent()
7491 * @see #computeHorizontalScrollOffset()
7492 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007493 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007494 */
Romain Guy8fb95422010-08-17 18:38:51 -07007495 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7496 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007497 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007498 scrollBar.draw(canvas);
7499 }
Mike Reede8853fc2009-09-04 14:01:48 -04007500
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007501 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007502 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7503 * returns true.</p>
7504 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007505 * @param canvas the canvas on which to draw the scrollbar
7506 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507 *
7508 * @see #isVerticalScrollBarEnabled()
7509 * @see #computeVerticalScrollRange()
7510 * @see #computeVerticalScrollExtent()
7511 * @see #computeVerticalScrollOffset()
7512 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007513 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007514 */
Romain Guy8fb95422010-08-17 18:38:51 -07007515 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7516 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007517 scrollBar.setBounds(l, t, r, b);
7518 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007519 }
7520
7521 /**
7522 * Implement this to do your drawing.
7523 *
7524 * @param canvas the canvas on which the background will be drawn
7525 */
7526 protected void onDraw(Canvas canvas) {
7527 }
7528
7529 /*
7530 * Caller is responsible for calling requestLayout if necessary.
7531 * (This allows addViewInLayout to not request a new layout.)
7532 */
7533 void assignParent(ViewParent parent) {
7534 if (mParent == null) {
7535 mParent = parent;
7536 } else if (parent == null) {
7537 mParent = null;
7538 } else {
7539 throw new RuntimeException("view " + this + " being added, but"
7540 + " it already has a parent");
7541 }
7542 }
7543
7544 /**
7545 * This is called when the view is attached to a window. At this point it
7546 * has a Surface and will start drawing. Note that this function is
7547 * guaranteed to be called before {@link #onDraw}, however it may be called
7548 * any time before the first onDraw -- including before or after
7549 * {@link #onMeasure}.
7550 *
7551 * @see #onDetachedFromWindow()
7552 */
7553 protected void onAttachedToWindow() {
7554 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7555 mParent.requestTransparentRegion(this);
7556 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007557 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7558 initialAwakenScrollBars();
7559 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7560 }
Chet Haasea9b61ac2010-12-20 07:40:25 -08007561 jumpDrawablesToCurrentState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 }
7563
7564 /**
7565 * This is called when the view is detached from a window. At this point it
7566 * no longer has a surface for drawing.
7567 *
7568 * @see #onAttachedToWindow()
7569 */
7570 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007571 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guy6c319ca2011-01-11 14:29:25 -08007572
Romain Guya440b002010-02-24 15:57:54 -08007573 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007574 removeLongPressCallback();
Romain Guy6c319ca2011-01-11 14:29:25 -08007575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007576 destroyDrawingCache();
Romain Guy6c319ca2011-01-11 14:29:25 -08007577
7578 if (mHardwareLayer != null) {
7579 mHardwareLayer.destroy();
7580 mHardwareLayer = null;
7581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582 }
7583
7584 /**
7585 * @return The number of times this view has been attached to a window
7586 */
7587 protected int getWindowAttachCount() {
7588 return mWindowAttachCount;
7589 }
7590
7591 /**
7592 * Retrieve a unique token identifying the window this view is attached to.
7593 * @return Return the window's token for use in
7594 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7595 */
7596 public IBinder getWindowToken() {
7597 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7598 }
7599
7600 /**
7601 * Retrieve a unique token identifying the top-level "real" window of
7602 * the window that this view is attached to. That is, this is like
7603 * {@link #getWindowToken}, except if the window this view in is a panel
7604 * window (attached to another containing window), then the token of
7605 * the containing window is returned instead.
7606 *
7607 * @return Returns the associated window token, either
7608 * {@link #getWindowToken()} or the containing window's token.
7609 */
7610 public IBinder getApplicationWindowToken() {
7611 AttachInfo ai = mAttachInfo;
7612 if (ai != null) {
7613 IBinder appWindowToken = ai.mPanelParentWindowToken;
7614 if (appWindowToken == null) {
7615 appWindowToken = ai.mWindowToken;
7616 }
7617 return appWindowToken;
7618 }
7619 return null;
7620 }
7621
7622 /**
7623 * Retrieve private session object this view hierarchy is using to
7624 * communicate with the window manager.
7625 * @return the session object to communicate with the window manager
7626 */
7627 /*package*/ IWindowSession getWindowSession() {
7628 return mAttachInfo != null ? mAttachInfo.mSession : null;
7629 }
7630
7631 /**
7632 * @param info the {@link android.view.View.AttachInfo} to associated with
7633 * this view
7634 */
7635 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7636 //System.out.println("Attached! " + this);
7637 mAttachInfo = info;
7638 mWindowAttachCount++;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007639 // We will need to evaluate the drawable state at least once.
7640 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641 if (mFloatingTreeObserver != null) {
7642 info.mTreeObserver.merge(mFloatingTreeObserver);
7643 mFloatingTreeObserver = null;
7644 }
7645 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7646 mAttachInfo.mScrollContainers.add(this);
7647 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7648 }
7649 performCollectViewAttributes(visibility);
7650 onAttachedToWindow();
7651 int vis = info.mWindowVisibility;
7652 if (vis != GONE) {
7653 onWindowVisibilityChanged(vis);
7654 }
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007655 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7656 // If nobody has evaluated the drawable state yet, then do it now.
7657 refreshDrawableState();
7658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007659 }
7660
7661 void dispatchDetachedFromWindow() {
7662 //System.out.println("Detached! " + this);
7663 AttachInfo info = mAttachInfo;
7664 if (info != null) {
7665 int vis = info.mWindowVisibility;
7666 if (vis != GONE) {
7667 onWindowVisibilityChanged(GONE);
7668 }
7669 }
7670
7671 onDetachedFromWindow();
7672 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7673 mAttachInfo.mScrollContainers.remove(this);
7674 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7675 }
7676 mAttachInfo = null;
7677 }
7678
7679 /**
7680 * Store this view hierarchy's frozen state into the given container.
7681 *
7682 * @param container The SparseArray in which to save the view's state.
7683 *
7684 * @see #restoreHierarchyState
7685 * @see #dispatchSaveInstanceState
7686 * @see #onSaveInstanceState
7687 */
7688 public void saveHierarchyState(SparseArray<Parcelable> container) {
7689 dispatchSaveInstanceState(container);
7690 }
7691
7692 /**
7693 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7694 * May be overridden to modify how freezing happens to a view's children; for example, some
7695 * views may want to not store state for their children.
7696 *
7697 * @param container The SparseArray in which to save the view's state.
7698 *
7699 * @see #dispatchRestoreInstanceState
7700 * @see #saveHierarchyState
7701 * @see #onSaveInstanceState
7702 */
7703 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7704 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7705 mPrivateFlags &= ~SAVE_STATE_CALLED;
7706 Parcelable state = onSaveInstanceState();
7707 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7708 throw new IllegalStateException(
7709 "Derived class did not call super.onSaveInstanceState()");
7710 }
7711 if (state != null) {
7712 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7713 // + ": " + state);
7714 container.put(mID, state);
7715 }
7716 }
7717 }
7718
7719 /**
7720 * Hook allowing a view to generate a representation of its internal state
7721 * that can later be used to create a new instance with that same state.
7722 * This state should only contain information that is not persistent or can
7723 * not be reconstructed later. For example, you will never store your
7724 * current position on screen because that will be computed again when a
7725 * new instance of the view is placed in its view hierarchy.
7726 * <p>
7727 * Some examples of things you may store here: the current cursor position
7728 * in a text view (but usually not the text itself since that is stored in a
7729 * content provider or other persistent storage), the currently selected
7730 * item in a list view.
7731 *
7732 * @return Returns a Parcelable object containing the view's current dynamic
7733 * state, or null if there is nothing interesting to save. The
7734 * default implementation returns null.
7735 * @see #onRestoreInstanceState
7736 * @see #saveHierarchyState
7737 * @see #dispatchSaveInstanceState
7738 * @see #setSaveEnabled(boolean)
7739 */
7740 protected Parcelable onSaveInstanceState() {
7741 mPrivateFlags |= SAVE_STATE_CALLED;
7742 return BaseSavedState.EMPTY_STATE;
7743 }
7744
7745 /**
7746 * Restore this view hierarchy's frozen state from the given container.
7747 *
7748 * @param container The SparseArray which holds previously frozen states.
7749 *
7750 * @see #saveHierarchyState
7751 * @see #dispatchRestoreInstanceState
7752 * @see #onRestoreInstanceState
7753 */
7754 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7755 dispatchRestoreInstanceState(container);
7756 }
7757
7758 /**
7759 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7760 * children. May be overridden to modify how restoreing happens to a view's children; for
7761 * example, some views may want to not store state for their children.
7762 *
7763 * @param container The SparseArray which holds previously saved state.
7764 *
7765 * @see #dispatchSaveInstanceState
7766 * @see #restoreHierarchyState
7767 * @see #onRestoreInstanceState
7768 */
7769 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7770 if (mID != NO_ID) {
7771 Parcelable state = container.get(mID);
7772 if (state != null) {
7773 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7774 // + ": " + state);
7775 mPrivateFlags &= ~SAVE_STATE_CALLED;
7776 onRestoreInstanceState(state);
7777 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7778 throw new IllegalStateException(
7779 "Derived class did not call super.onRestoreInstanceState()");
7780 }
7781 }
7782 }
7783 }
7784
7785 /**
7786 * Hook allowing a view to re-apply a representation of its internal state that had previously
7787 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7788 * null state.
7789 *
7790 * @param state The frozen state that had previously been returned by
7791 * {@link #onSaveInstanceState}.
7792 *
7793 * @see #onSaveInstanceState
7794 * @see #restoreHierarchyState
7795 * @see #dispatchRestoreInstanceState
7796 */
7797 protected void onRestoreInstanceState(Parcelable state) {
7798 mPrivateFlags |= SAVE_STATE_CALLED;
7799 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007800 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7801 + "received " + state.getClass().toString() + " instead. This usually happens "
7802 + "when two views of different type have the same id in the same hierarchy. "
7803 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7804 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 }
7806 }
7807
7808 /**
7809 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7810 *
7811 * @return the drawing start time in milliseconds
7812 */
7813 public long getDrawingTime() {
7814 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7815 }
7816
7817 /**
7818 * <p>Enables or disables the duplication of the parent's state into this view. When
7819 * duplication is enabled, this view gets its drawable state from its parent rather
7820 * than from its own internal properties.</p>
7821 *
7822 * <p>Note: in the current implementation, setting this property to true after the
7823 * view was added to a ViewGroup might have no effect at all. This property should
7824 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7825 *
7826 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7827 * property is enabled, an exception will be thrown.</p>
7828 *
7829 * @param enabled True to enable duplication of the parent's drawable state, false
7830 * to disable it.
7831 *
7832 * @see #getDrawableState()
7833 * @see #isDuplicateParentStateEnabled()
7834 */
7835 public void setDuplicateParentStateEnabled(boolean enabled) {
7836 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7837 }
7838
7839 /**
7840 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7841 *
7842 * @return True if this view's drawable state is duplicated from the parent,
7843 * false otherwise
7844 *
7845 * @see #getDrawableState()
7846 * @see #setDuplicateParentStateEnabled(boolean)
7847 */
7848 public boolean isDuplicateParentStateEnabled() {
7849 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7850 }
7851
7852 /**
Romain Guy171c5922011-01-06 10:04:23 -08007853 * <p>Specifies the type of layer backing this view. The layer can be
7854 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
7855 * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
7856 *
7857 * <p>A layer is associated with an optional {@link android.graphics.Paint}
7858 * instance that controls how the layer is composed on screen. The following
7859 * properties of the paint are taken into account when composing the layer:</p>
7860 * <ul>
7861 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
7862 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
7863 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
7864 * </ul>
7865 *
7866 * <p>If this view has an alpha value set to < 1.0 by calling
7867 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
7868 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
7869 * equivalent to setting a hardware layer on this view and providing a paint with
7870 * the desired alpha value.<p>
7871 *
7872 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
7873 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
7874 * for more information on when and how to use layers.</p>
7875 *
7876 * @param layerType The ype of layer to use with this view, must be one of
7877 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
7878 * {@link #LAYER_TYPE_HARDWARE}
7879 * @param paint The paint used to compose the layer. This argument is optional
7880 * and can be null. It is ignored when the layer type is
7881 * {@link #LAYER_TYPE_NONE}
7882 *
7883 * @see #getLayerType()
7884 * @see #LAYER_TYPE_NONE
7885 * @see #LAYER_TYPE_SOFTWARE
7886 * @see #LAYER_TYPE_HARDWARE
7887 * @see #setAlpha(float)
7888 *
7889 * @attr ref android.R.styleable#View_layerType
7890 */
7891 public void setLayerType(int layerType, Paint paint) {
7892 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
7893 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
7894 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
7895 }
Romain Guy6c319ca2011-01-11 14:29:25 -08007896
7897 if (layerType == mLayerType) return;
Romain Guy171c5922011-01-06 10:04:23 -08007898
7899 // Destroy any previous software drawing cache if needed
Romain Guy6c319ca2011-01-11 14:29:25 -08007900 switch (mLayerType) {
7901 case LAYER_TYPE_SOFTWARE:
7902 if (mDrawingCache != null) {
7903 mDrawingCache.recycle();
7904 mDrawingCache = null;
7905 }
7906
7907 if (mUnscaledDrawingCache != null) {
7908 mUnscaledDrawingCache.recycle();
7909 mUnscaledDrawingCache = null;
7910 }
7911 break;
7912 case LAYER_TYPE_HARDWARE:
7913 if (mHardwareLayer != null) {
7914 mHardwareLayer.destroy();
7915 mHardwareLayer = null;
7916 }
7917 break;
7918 default:
7919 break;
Romain Guy171c5922011-01-06 10:04:23 -08007920 }
7921
7922 mLayerType = layerType;
7923 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
7924
Romain Guy6c319ca2011-01-11 14:29:25 -08007925 // TODO: Make sure we invalidate the parent's display list
Romain Guy171c5922011-01-06 10:04:23 -08007926 invalidate();
7927 }
7928
7929 /**
7930 * Indicates what type of layer is currently associated with this view. By default
7931 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
7932 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
7933 * for more information on the different types of layers.
7934 *
7935 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
7936 * {@link #LAYER_TYPE_HARDWARE}
7937 *
7938 * @see #setLayerType(int, android.graphics.Paint)
7939 * @see #LAYER_TYPE_NONE
7940 * @see #LAYER_TYPE_SOFTWARE
7941 * @see #LAYER_TYPE_HARDWARE
7942 */
7943 public int getLayerType() {
7944 return mLayerType;
7945 }
Romain Guy6c319ca2011-01-11 14:29:25 -08007946
7947 /**
7948 * <p>Returns a hardware layer that can be used to draw this view again
7949 * without executing its draw method.</p>
7950 *
7951 * @return A HardwareLayer ready to render, or null if an error occurred.
7952 */
7953 HardwareLayer getHardwareLayer(Canvas currentCanvas) {
7954 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
7955 return null;
7956 }
7957
7958 final int width = mRight - mLeft;
7959 final int height = mBottom - mTop;
7960
7961 if (width == 0 || height == 0) {
7962 return null;
7963 }
7964
7965 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
7966 if (mHardwareLayer == null) {
7967 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
7968 width, height, isOpaque());
7969 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
7970 mHardwareLayer.resize(width, height);
7971 }
7972
7973 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
7974 try {
7975 canvas.setViewport(width, height);
7976 canvas.onPreDraw();
7977
7978 computeScroll();
7979 canvas.translate(-mScrollX, -mScrollY);
7980
7981 final int restoreCount = canvas.save();
7982
7983 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
7984
7985 // Fast path for layouts with no backgrounds
7986 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7987 mPrivateFlags &= ~DIRTY_MASK;
7988 dispatchDraw(canvas);
7989 } else {
7990 draw(canvas);
7991 }
7992
7993 canvas.restoreToCount(restoreCount);
7994 } finally {
7995 canvas.onPostDraw();
7996 mHardwareLayer.end(currentCanvas);
7997 }
7998 }
7999
8000 return mHardwareLayer;
8001 }
Romain Guy171c5922011-01-06 10:04:23 -08008002
8003 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008004 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
8005 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
8006 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
8007 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
8008 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
8009 * null.</p>
Romain Guy171c5922011-01-06 10:04:23 -08008010 *
8011 * <p>Enabling the drawing cache is similar to
8012 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
8013 * acceleration is turned off. When hardware acceleration is turned on enabling the
8014 * drawing cache has either no effect or the cache used at drawing time is not a bitmap.
8015 * This API can however be used to manually generate a bitmap copy of this view.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008016 *
8017 * @param enabled true to enable the drawing cache, false otherwise
8018 *
8019 * @see #isDrawingCacheEnabled()
8020 * @see #getDrawingCache()
8021 * @see #buildDrawingCache()
Romain Guy171c5922011-01-06 10:04:23 -08008022 * @see #setLayerType(int, android.graphics.Paint)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008023 */
8024 public void setDrawingCacheEnabled(boolean enabled) {
8025 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
8026 }
8027
8028 /**
8029 * <p>Indicates whether the drawing cache is enabled for this view.</p>
8030 *
8031 * @return true if the drawing cache is enabled
8032 *
8033 * @see #setDrawingCacheEnabled(boolean)
8034 * @see #getDrawingCache()
8035 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07008036 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008037 public boolean isDrawingCacheEnabled() {
8038 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
8039 }
8040
8041 /**
Romain Guyb051e892010-09-28 19:09:36 -07008042 * <p>Returns a display list that can be used to draw this view again
8043 * without executing its draw method.</p>
8044 *
8045 * @return A DisplayList ready to replay, or null if caching is not enabled.
8046 */
8047 DisplayList getDisplayList() {
8048 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8049 return null;
8050 }
Romain Guyb051e892010-09-28 19:09:36 -07008051 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8052 return null;
8053 }
8054
8055 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED &&
Chet Haase9e90a992011-01-04 16:23:21 -08008056 ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
8057 mDisplayList == null || !mDisplayList.isValid())) {
Romain Guyb051e892010-09-28 19:09:36 -07008058
Chet Haase9e90a992011-01-04 16:23:21 -08008059 if (mDisplayList == null) {
8060 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
8061 }
Romain Guyb051e892010-09-28 19:09:36 -07008062
8063 final HardwareCanvas canvas = mDisplayList.start();
8064 try {
8065 int width = mRight - mLeft;
8066 int height = mBottom - mTop;
8067
8068 canvas.setViewport(width, height);
8069 canvas.onPreDraw();
8070
8071 final int restoreCount = canvas.save();
8072
Romain Guy2fe9a8f2010-10-04 20:17:01 -07008073 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Romain Guyb051e892010-09-28 19:09:36 -07008074
8075 // Fast path for layouts with no backgrounds
8076 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8077 mPrivateFlags &= ~DIRTY_MASK;
8078 dispatchDraw(canvas);
8079 } else {
8080 draw(canvas);
8081 }
8082
8083 canvas.restoreToCount(restoreCount);
8084 } finally {
8085 canvas.onPostDraw();
8086
8087 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07008088 }
8089 }
8090
8091 return mDisplayList;
8092 }
8093
8094 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008095 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
8096 *
8097 * @return A non-scaled bitmap representing this view or null if cache is disabled.
8098 *
8099 * @see #getDrawingCache(boolean)
8100 */
8101 public Bitmap getDrawingCache() {
8102 return getDrawingCache(false);
8103 }
8104
8105 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008106 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
8107 * is null when caching is disabled. If caching is enabled and the cache is not ready,
8108 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
8109 * draw from the cache when the cache is enabled. To benefit from the cache, you must
8110 * request the drawing cache by calling this method and draw it on screen if the
8111 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008112 *
8113 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8114 * this method will create a bitmap of the same size as this view. Because this bitmap
8115 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8116 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8117 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8118 * size than the view. This implies that your application must be able to handle this
8119 * size.</p>
8120 *
8121 * @param autoScale Indicates whether the generated bitmap should be scaled based on
8122 * the current density of the screen when the application is in compatibility
8123 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008124 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008125 * @return A bitmap representing this view or null if cache is disabled.
8126 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008127 * @see #setDrawingCacheEnabled(boolean)
8128 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07008129 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008130 * @see #destroyDrawingCache()
8131 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008132 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8134 return null;
8135 }
8136 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008137 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138 }
Romain Guy02890fd2010-08-06 17:58:44 -07008139 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008140 }
8141
8142 /**
8143 * <p>Frees the resources used by the drawing cache. If you call
8144 * {@link #buildDrawingCache()} manually without calling
8145 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8146 * should cleanup the cache with this method afterwards.</p>
8147 *
8148 * @see #setDrawingCacheEnabled(boolean)
8149 * @see #buildDrawingCache()
8150 * @see #getDrawingCache()
8151 */
8152 public void destroyDrawingCache() {
8153 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008154 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008155 mDrawingCache = null;
8156 }
Romain Guyfbd8f692009-06-26 14:51:58 -07008157 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008158 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07008159 mUnscaledDrawingCache = null;
8160 }
Romain Guyb051e892010-09-28 19:09:36 -07008161 if (mDisplayList != null) {
Chet Haase9e90a992011-01-04 16:23:21 -08008162 mDisplayList.invalidate();
Romain Guyb051e892010-09-28 19:09:36 -07008163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008164 }
8165
8166 /**
8167 * Setting a solid background color for the drawing cache's bitmaps will improve
8168 * perfromance and memory usage. Note, though that this should only be used if this
8169 * view will always be drawn on top of a solid color.
8170 *
8171 * @param color The background color to use for the drawing cache's bitmap
8172 *
8173 * @see #setDrawingCacheEnabled(boolean)
8174 * @see #buildDrawingCache()
8175 * @see #getDrawingCache()
8176 */
8177 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08008178 if (color != mDrawingCacheBackgroundColor) {
8179 mDrawingCacheBackgroundColor = color;
8180 mPrivateFlags &= ~DRAWING_CACHE_VALID;
8181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008182 }
8183
8184 /**
8185 * @see #setDrawingCacheBackgroundColor(int)
8186 *
8187 * @return The background color to used for the drawing cache's bitmap
8188 */
8189 public int getDrawingCacheBackgroundColor() {
8190 return mDrawingCacheBackgroundColor;
8191 }
8192
8193 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008194 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
8195 *
8196 * @see #buildDrawingCache(boolean)
8197 */
8198 public void buildDrawingCache() {
8199 buildDrawingCache(false);
8200 }
8201
8202 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008203 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
8204 *
8205 * <p>If you call {@link #buildDrawingCache()} manually without calling
8206 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8207 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07008208 *
8209 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8210 * this method will create a bitmap of the same size as this view. Because this bitmap
8211 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8212 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8213 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8214 * size than the view. This implies that your application must be able to handle this
8215 * size.</p>
Romain Guy0d9275e2010-10-26 14:22:30 -07008216 *
8217 * <p>You should avoid calling this method when hardware acceleration is enabled. If
8218 * you do not need the drawing cache bitmap, calling this method will increase memory
8219 * usage and cause the view to be rendered in software once, thus negatively impacting
8220 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008221 *
8222 * @see #getDrawingCache()
8223 * @see #destroyDrawingCache()
8224 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008225 public void buildDrawingCache(boolean autoScale) {
8226 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07008227 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008228
8229 if (ViewDebug.TRACE_HIERARCHY) {
8230 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
8231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008232
Romain Guy8506ab42009-06-11 17:35:47 -07008233 int width = mRight - mLeft;
8234 int height = mBottom - mTop;
8235
8236 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07008237 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07008238
Romain Guye1123222009-06-29 14:24:56 -07008239 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008240 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
8241 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07008242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008243
8244 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07008245 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08008246 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008247
8248 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07008249 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08008250 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008251 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
8252 destroyDrawingCache();
8253 return;
8254 }
8255
8256 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07008257 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008258
8259 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008260 Bitmap.Config quality;
8261 if (!opaque) {
8262 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
8263 case DRAWING_CACHE_QUALITY_AUTO:
8264 quality = Bitmap.Config.ARGB_8888;
8265 break;
8266 case DRAWING_CACHE_QUALITY_LOW:
8267 quality = Bitmap.Config.ARGB_4444;
8268 break;
8269 case DRAWING_CACHE_QUALITY_HIGH:
8270 quality = Bitmap.Config.ARGB_8888;
8271 break;
8272 default:
8273 quality = Bitmap.Config.ARGB_8888;
8274 break;
8275 }
8276 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07008277 // Optimization for translucent windows
8278 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08008279 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008280 }
8281
8282 // Try to cleanup memory
8283 if (bitmap != null) bitmap.recycle();
8284
8285 try {
8286 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07008287 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07008288 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07008289 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008290 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07008291 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008292 }
Adam Powell26153a32010-11-08 15:22:27 -08008293 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008294 } catch (OutOfMemoryError e) {
8295 // If there is not enough memory to create the bitmap cache, just
8296 // ignore the issue as bitmap caches are not required to draw the
8297 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07008298 if (autoScale) {
8299 mDrawingCache = null;
8300 } else {
8301 mUnscaledDrawingCache = null;
8302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008303 return;
8304 }
8305
8306 clear = drawingCacheBackgroundColor != 0;
8307 }
8308
8309 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008310 if (attachInfo != null) {
8311 canvas = attachInfo.mCanvas;
8312 if (canvas == null) {
8313 canvas = new Canvas();
8314 }
8315 canvas.setBitmap(bitmap);
8316 // Temporarily clobber the cached Canvas in case one of our children
8317 // is also using a drawing cache. Without this, the children would
8318 // steal the canvas by attaching their own bitmap to it and bad, bad
8319 // thing would happen (invisible views, corrupted drawings, etc.)
8320 attachInfo.mCanvas = null;
8321 } else {
8322 // This case should hopefully never or seldom happen
8323 canvas = new Canvas(bitmap);
8324 }
8325
8326 if (clear) {
8327 bitmap.eraseColor(drawingCacheBackgroundColor);
8328 }
8329
8330 computeScroll();
8331 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07008332
Romain Guye1123222009-06-29 14:24:56 -07008333 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008334 final float scale = attachInfo.mApplicationScale;
8335 canvas.scale(scale, scale);
8336 }
8337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338 canvas.translate(-mScrollX, -mScrollY);
8339
Romain Guy5bcdff42009-05-14 21:27:18 -07008340 mPrivateFlags |= DRAWN;
Romain Guy171c5922011-01-06 10:04:23 -08008341 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
8342 mLayerType != LAYER_TYPE_NONE) {
Romain Guy0d9275e2010-10-26 14:22:30 -07008343 mPrivateFlags |= DRAWING_CACHE_VALID;
8344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008345
8346 // Fast path for layouts with no backgrounds
8347 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8348 if (ViewDebug.TRACE_HIERARCHY) {
8349 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8350 }
Romain Guy5bcdff42009-05-14 21:27:18 -07008351 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 dispatchDraw(canvas);
8353 } else {
8354 draw(canvas);
8355 }
8356
8357 canvas.restoreToCount(restoreCount);
8358
8359 if (attachInfo != null) {
8360 // Restore the cached Canvas for our siblings
8361 attachInfo.mCanvas = canvas;
8362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008363 }
8364 }
8365
8366 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008367 * Create a snapshot of the view into a bitmap. We should probably make
8368 * some form of this public, but should think about the API.
8369 */
Romain Guy223ff5c2010-03-02 17:07:47 -08008370 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008371 int width = mRight - mLeft;
8372 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008373
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008374 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07008375 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008376 width = (int) ((width * scale) + 0.5f);
8377 height = (int) ((height * scale) + 0.5f);
8378
Romain Guy8c11e312009-09-14 15:15:30 -07008379 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008380 if (bitmap == null) {
8381 throw new OutOfMemoryError();
8382 }
8383
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008384 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
8385
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008386 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008387 if (attachInfo != null) {
8388 canvas = attachInfo.mCanvas;
8389 if (canvas == null) {
8390 canvas = new Canvas();
8391 }
8392 canvas.setBitmap(bitmap);
8393 // Temporarily clobber the cached Canvas in case one of our children
8394 // is also using a drawing cache. Without this, the children would
8395 // steal the canvas by attaching their own bitmap to it and bad, bad
8396 // things would happen (invisible views, corrupted drawings, etc.)
8397 attachInfo.mCanvas = null;
8398 } else {
8399 // This case should hopefully never or seldom happen
8400 canvas = new Canvas(bitmap);
8401 }
8402
Romain Guy5bcdff42009-05-14 21:27:18 -07008403 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008404 bitmap.eraseColor(backgroundColor);
8405 }
8406
8407 computeScroll();
8408 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008409 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008410 canvas.translate(-mScrollX, -mScrollY);
8411
Romain Guy5bcdff42009-05-14 21:27:18 -07008412 // Temporarily remove the dirty mask
8413 int flags = mPrivateFlags;
8414 mPrivateFlags &= ~DIRTY_MASK;
8415
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008416 // Fast path for layouts with no backgrounds
8417 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8418 dispatchDraw(canvas);
8419 } else {
8420 draw(canvas);
8421 }
8422
Romain Guy5bcdff42009-05-14 21:27:18 -07008423 mPrivateFlags = flags;
8424
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008425 canvas.restoreToCount(restoreCount);
8426
8427 if (attachInfo != null) {
8428 // Restore the cached Canvas for our siblings
8429 attachInfo.mCanvas = canvas;
8430 }
Romain Guy8506ab42009-06-11 17:35:47 -07008431
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008432 return bitmap;
8433 }
8434
8435 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008436 * Indicates whether this View is currently in edit mode. A View is usually
8437 * in edit mode when displayed within a developer tool. For instance, if
8438 * this View is being drawn by a visual user interface builder, this method
8439 * should return true.
8440 *
8441 * Subclasses should check the return value of this method to provide
8442 * different behaviors if their normal behavior might interfere with the
8443 * host environment. For instance: the class spawns a thread in its
8444 * constructor, the drawing code relies on device-specific features, etc.
8445 *
8446 * This method is usually checked in the drawing code of custom widgets.
8447 *
8448 * @return True if this View is in edit mode, false otherwise.
8449 */
8450 public boolean isInEditMode() {
8451 return false;
8452 }
8453
8454 /**
8455 * If the View draws content inside its padding and enables fading edges,
8456 * it needs to support padding offsets. Padding offsets are added to the
8457 * fading edges to extend the length of the fade so that it covers pixels
8458 * drawn inside the padding.
8459 *
8460 * Subclasses of this class should override this method if they need
8461 * to draw content inside the padding.
8462 *
8463 * @return True if padding offset must be applied, false otherwise.
8464 *
8465 * @see #getLeftPaddingOffset()
8466 * @see #getRightPaddingOffset()
8467 * @see #getTopPaddingOffset()
8468 * @see #getBottomPaddingOffset()
8469 *
8470 * @since CURRENT
8471 */
8472 protected boolean isPaddingOffsetRequired() {
8473 return false;
8474 }
8475
8476 /**
8477 * Amount by which to extend the left fading region. Called only when
8478 * {@link #isPaddingOffsetRequired()} returns true.
8479 *
8480 * @return The left padding offset in pixels.
8481 *
8482 * @see #isPaddingOffsetRequired()
8483 *
8484 * @since CURRENT
8485 */
8486 protected int getLeftPaddingOffset() {
8487 return 0;
8488 }
8489
8490 /**
8491 * Amount by which to extend the right fading region. Called only when
8492 * {@link #isPaddingOffsetRequired()} returns true.
8493 *
8494 * @return The right padding offset in pixels.
8495 *
8496 * @see #isPaddingOffsetRequired()
8497 *
8498 * @since CURRENT
8499 */
8500 protected int getRightPaddingOffset() {
8501 return 0;
8502 }
8503
8504 /**
8505 * Amount by which to extend the top fading region. Called only when
8506 * {@link #isPaddingOffsetRequired()} returns true.
8507 *
8508 * @return The top padding offset in pixels.
8509 *
8510 * @see #isPaddingOffsetRequired()
8511 *
8512 * @since CURRENT
8513 */
8514 protected int getTopPaddingOffset() {
8515 return 0;
8516 }
8517
8518 /**
8519 * Amount by which to extend the bottom fading region. Called only when
8520 * {@link #isPaddingOffsetRequired()} returns true.
8521 *
8522 * @return The bottom padding offset in pixels.
8523 *
8524 * @see #isPaddingOffsetRequired()
8525 *
8526 * @since CURRENT
8527 */
8528 protected int getBottomPaddingOffset() {
8529 return 0;
8530 }
8531
8532 /**
Romain Guy2bffd262010-09-12 17:40:02 -07008533 * <p>Indicates whether this view is attached to an hardware accelerated
8534 * window or not.</p>
8535 *
8536 * <p>Even if this method returns true, it does not mean that every call
8537 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8538 * accelerated {@link android.graphics.Canvas}. For instance, if this view
8539 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8540 * window is hardware accelerated,
8541 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8542 * return false, and this method will return true.</p>
8543 *
8544 * @return True if the view is attached to a window and the window is
8545 * hardware accelerated; false in any other case.
8546 */
8547 public boolean isHardwareAccelerated() {
8548 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8549 }
8550
8551 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008552 * Manually render this view (and all of its children) to the given Canvas.
8553 * The view must have already done a full layout before this function is
Chet Haasec75ec332010-12-17 07:44:30 -08008554 * called. When implementing a view, implement {@link #onDraw} instead of
8555 * overriding this method. If you do need to override this method, call
8556 * the superclass version.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008557 *
8558 * @param canvas The Canvas to which the View is rendered.
8559 */
8560 public void draw(Canvas canvas) {
8561 if (ViewDebug.TRACE_HIERARCHY) {
8562 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8563 }
8564
Romain Guy5bcdff42009-05-14 21:27:18 -07008565 final int privateFlags = mPrivateFlags;
8566 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8567 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8568 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07008569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008570 /*
8571 * Draw traversal performs several drawing steps which must be executed
8572 * in the appropriate order:
8573 *
8574 * 1. Draw the background
8575 * 2. If necessary, save the canvas' layers to prepare for fading
8576 * 3. Draw view's content
8577 * 4. Draw children
8578 * 5. If necessary, draw the fading edges and restore layers
8579 * 6. Draw decorations (scrollbars for instance)
8580 */
8581
8582 // Step 1, draw the background, if needed
8583 int saveCount;
8584
Romain Guy24443ea2009-05-11 11:56:30 -07008585 if (!dirtyOpaque) {
8586 final Drawable background = mBGDrawable;
8587 if (background != null) {
8588 final int scrollX = mScrollX;
8589 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590
Romain Guy24443ea2009-05-11 11:56:30 -07008591 if (mBackgroundSizeChanged) {
8592 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8593 mBackgroundSizeChanged = false;
8594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008595
Romain Guy24443ea2009-05-11 11:56:30 -07008596 if ((scrollX | scrollY) == 0) {
8597 background.draw(canvas);
8598 } else {
8599 canvas.translate(scrollX, scrollY);
8600 background.draw(canvas);
8601 canvas.translate(-scrollX, -scrollY);
8602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008603 }
8604 }
8605
8606 // skip step 2 & 5 if possible (common case)
8607 final int viewFlags = mViewFlags;
8608 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8609 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8610 if (!verticalEdges && !horizontalEdges) {
8611 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008612 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008613
8614 // Step 4, draw the children
8615 dispatchDraw(canvas);
8616
8617 // Step 6, draw decorations (scrollbars)
8618 onDrawScrollBars(canvas);
8619
8620 // we're done...
8621 return;
8622 }
8623
8624 /*
8625 * Here we do the full fledged routine...
8626 * (this is an uncommon case where speed matters less,
8627 * this is why we repeat some of the tests that have been
8628 * done above)
8629 */
8630
8631 boolean drawTop = false;
8632 boolean drawBottom = false;
8633 boolean drawLeft = false;
8634 boolean drawRight = false;
8635
8636 float topFadeStrength = 0.0f;
8637 float bottomFadeStrength = 0.0f;
8638 float leftFadeStrength = 0.0f;
8639 float rightFadeStrength = 0.0f;
8640
8641 // Step 2, save the canvas' layers
8642 int paddingLeft = mPaddingLeft;
8643 int paddingTop = mPaddingTop;
8644
8645 final boolean offsetRequired = isPaddingOffsetRequired();
8646 if (offsetRequired) {
8647 paddingLeft += getLeftPaddingOffset();
8648 paddingTop += getTopPaddingOffset();
8649 }
8650
8651 int left = mScrollX + paddingLeft;
8652 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8653 int top = mScrollY + paddingTop;
8654 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8655
8656 if (offsetRequired) {
8657 right += getRightPaddingOffset();
8658 bottom += getBottomPaddingOffset();
8659 }
8660
8661 final ScrollabilityCache scrollabilityCache = mScrollCache;
8662 int length = scrollabilityCache.fadingEdgeLength;
8663
8664 // clip the fade length if top and bottom fades overlap
8665 // overlapping fades produce odd-looking artifacts
8666 if (verticalEdges && (top + length > bottom - length)) {
8667 length = (bottom - top) / 2;
8668 }
8669
8670 // also clip horizontal fades if necessary
8671 if (horizontalEdges && (left + length > right - length)) {
8672 length = (right - left) / 2;
8673 }
8674
8675 if (verticalEdges) {
8676 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008677 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008679 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 }
8681
8682 if (horizontalEdges) {
8683 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008684 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008685 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008686 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008687 }
8688
8689 saveCount = canvas.getSaveCount();
8690
8691 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008692 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008693 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8694
8695 if (drawTop) {
8696 canvas.saveLayer(left, top, right, top + length, null, flags);
8697 }
8698
8699 if (drawBottom) {
8700 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8701 }
8702
8703 if (drawLeft) {
8704 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8705 }
8706
8707 if (drawRight) {
8708 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8709 }
8710 } else {
8711 scrollabilityCache.setFadeColor(solidColor);
8712 }
8713
8714 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008715 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008716
8717 // Step 4, draw the children
8718 dispatchDraw(canvas);
8719
8720 // Step 5, draw the fade effect and restore layers
8721 final Paint p = scrollabilityCache.paint;
8722 final Matrix matrix = scrollabilityCache.matrix;
8723 final Shader fade = scrollabilityCache.shader;
8724 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8725
8726 if (drawTop) {
8727 matrix.setScale(1, fadeHeight * topFadeStrength);
8728 matrix.postTranslate(left, top);
8729 fade.setLocalMatrix(matrix);
8730 canvas.drawRect(left, top, right, top + length, p);
8731 }
8732
8733 if (drawBottom) {
8734 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8735 matrix.postRotate(180);
8736 matrix.postTranslate(left, bottom);
8737 fade.setLocalMatrix(matrix);
8738 canvas.drawRect(left, bottom - length, right, bottom, p);
8739 }
8740
8741 if (drawLeft) {
8742 matrix.setScale(1, fadeHeight * leftFadeStrength);
8743 matrix.postRotate(-90);
8744 matrix.postTranslate(left, top);
8745 fade.setLocalMatrix(matrix);
8746 canvas.drawRect(left, top, left + length, bottom, p);
8747 }
8748
8749 if (drawRight) {
8750 matrix.setScale(1, fadeHeight * rightFadeStrength);
8751 matrix.postRotate(90);
8752 matrix.postTranslate(right, top);
8753 fade.setLocalMatrix(matrix);
8754 canvas.drawRect(right - length, top, right, bottom, p);
8755 }
8756
8757 canvas.restoreToCount(saveCount);
8758
8759 // Step 6, draw decorations (scrollbars)
8760 onDrawScrollBars(canvas);
8761 }
8762
8763 /**
8764 * Override this if your view is known to always be drawn on top of a solid color background,
8765 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8766 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8767 * should be set to 0xFF.
8768 *
8769 * @see #setVerticalFadingEdgeEnabled
8770 * @see #setHorizontalFadingEdgeEnabled
8771 *
8772 * @return The known solid color background for this view, or 0 if the color may vary
8773 */
8774 public int getSolidColor() {
8775 return 0;
8776 }
8777
8778 /**
8779 * Build a human readable string representation of the specified view flags.
8780 *
8781 * @param flags the view flags to convert to a string
8782 * @return a String representing the supplied flags
8783 */
8784 private static String printFlags(int flags) {
8785 String output = "";
8786 int numFlags = 0;
8787 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8788 output += "TAKES_FOCUS";
8789 numFlags++;
8790 }
8791
8792 switch (flags & VISIBILITY_MASK) {
8793 case INVISIBLE:
8794 if (numFlags > 0) {
8795 output += " ";
8796 }
8797 output += "INVISIBLE";
8798 // USELESS HERE numFlags++;
8799 break;
8800 case GONE:
8801 if (numFlags > 0) {
8802 output += " ";
8803 }
8804 output += "GONE";
8805 // USELESS HERE numFlags++;
8806 break;
8807 default:
8808 break;
8809 }
8810 return output;
8811 }
8812
8813 /**
8814 * Build a human readable string representation of the specified private
8815 * view flags.
8816 *
8817 * @param privateFlags the private view flags to convert to a string
8818 * @return a String representing the supplied flags
8819 */
8820 private static String printPrivateFlags(int privateFlags) {
8821 String output = "";
8822 int numFlags = 0;
8823
8824 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8825 output += "WANTS_FOCUS";
8826 numFlags++;
8827 }
8828
8829 if ((privateFlags & FOCUSED) == FOCUSED) {
8830 if (numFlags > 0) {
8831 output += " ";
8832 }
8833 output += "FOCUSED";
8834 numFlags++;
8835 }
8836
8837 if ((privateFlags & SELECTED) == SELECTED) {
8838 if (numFlags > 0) {
8839 output += " ";
8840 }
8841 output += "SELECTED";
8842 numFlags++;
8843 }
8844
8845 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8846 if (numFlags > 0) {
8847 output += " ";
8848 }
8849 output += "IS_ROOT_NAMESPACE";
8850 numFlags++;
8851 }
8852
8853 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8854 if (numFlags > 0) {
8855 output += " ";
8856 }
8857 output += "HAS_BOUNDS";
8858 numFlags++;
8859 }
8860
8861 if ((privateFlags & DRAWN) == DRAWN) {
8862 if (numFlags > 0) {
8863 output += " ";
8864 }
8865 output += "DRAWN";
8866 // USELESS HERE numFlags++;
8867 }
8868 return output;
8869 }
8870
8871 /**
8872 * <p>Indicates whether or not this view's layout will be requested during
8873 * the next hierarchy layout pass.</p>
8874 *
8875 * @return true if the layout will be forced during next layout pass
8876 */
8877 public boolean isLayoutRequested() {
8878 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8879 }
8880
8881 /**
8882 * Assign a size and position to a view and all of its
8883 * descendants
8884 *
8885 * <p>This is the second phase of the layout mechanism.
8886 * (The first is measuring). In this phase, each parent calls
8887 * layout on all of its children to position them.
8888 * This is typically done using the child measurements
Chet Haase9c087442011-01-12 16:20:16 -08008889 * that were stored in the measure pass().</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008890 *
Chet Haase9c087442011-01-12 16:20:16 -08008891 * <p>Derived classes should not override this method.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 * Derived classes with children should override
8893 * onLayout. In that method, they should
Chet Haase9c087442011-01-12 16:20:16 -08008894 * call layout on each of their children.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008895 *
8896 * @param l Left position, relative to parent
8897 * @param t Top position, relative to parent
8898 * @param r Right position, relative to parent
8899 * @param b Bottom position, relative to parent
8900 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008901 @SuppressWarnings({"unchecked"})
Chet Haase9c087442011-01-12 16:20:16 -08008902 public void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008903 int oldL = mLeft;
8904 int oldT = mTop;
8905 int oldB = mBottom;
8906 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008907 boolean changed = setFrame(l, t, r, b);
8908 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8909 if (ViewDebug.TRACE_HIERARCHY) {
8910 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8911 }
8912
8913 onLayout(changed, l, t, r, b);
8914 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008915
8916 if (mOnLayoutChangeListeners != null) {
8917 ArrayList<OnLayoutChangeListener> listenersCopy =
8918 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8919 int numListeners = listenersCopy.size();
8920 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07008921 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07008922 }
8923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008924 }
8925 mPrivateFlags &= ~FORCE_LAYOUT;
8926 }
8927
8928 /**
8929 * Called from layout when this view should
8930 * assign a size and position to each of its children.
8931 *
8932 * Derived classes with children should override
8933 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008934 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935 * @param changed This is a new size or position for this view
8936 * @param left Left position, relative to parent
8937 * @param top Top position, relative to parent
8938 * @param right Right position, relative to parent
8939 * @param bottom Bottom position, relative to parent
8940 */
8941 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8942 }
8943
8944 /**
8945 * Assign a size and position to this view.
8946 *
8947 * This is called from layout.
8948 *
8949 * @param left Left position, relative to parent
8950 * @param top Top position, relative to parent
8951 * @param right Right position, relative to parent
8952 * @param bottom Bottom position, relative to parent
8953 * @return true if the new size and position are different than the
8954 * previous ones
8955 * {@hide}
8956 */
8957 protected boolean setFrame(int left, int top, int right, int bottom) {
8958 boolean changed = false;
8959
8960 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008961 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008962 + right + "," + bottom + ")");
8963 }
8964
8965 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8966 changed = true;
8967
8968 // Remember our drawn bit
8969 int drawn = mPrivateFlags & DRAWN;
8970
8971 // Invalidate our old position
8972 invalidate();
8973
8974
8975 int oldWidth = mRight - mLeft;
8976 int oldHeight = mBottom - mTop;
8977
8978 mLeft = left;
8979 mTop = top;
8980 mRight = right;
8981 mBottom = bottom;
8982
8983 mPrivateFlags |= HAS_BOUNDS;
8984
8985 int newWidth = right - left;
8986 int newHeight = bottom - top;
8987
8988 if (newWidth != oldWidth || newHeight != oldHeight) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08008989 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8990 // A change in dimension means an auto-centered pivot point changes, too
8991 mMatrixDirty = true;
8992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008993 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8994 }
8995
8996 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8997 // If we are visible, force the DRAWN bit to on so that
8998 // this invalidate will go through (at least to our parent).
8999 // This is because someone may have invalidated this view
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009000 // before this call to setFrame came in, thereby clearing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001 // the DRAWN bit.
9002 mPrivateFlags |= DRAWN;
9003 invalidate();
9004 }
9005
9006 // Reset drawn bit to original value (invalidate turns it off)
9007 mPrivateFlags |= drawn;
9008
9009 mBackgroundSizeChanged = true;
9010 }
9011 return changed;
9012 }
9013
9014 /**
9015 * Finalize inflating a view from XML. This is called as the last phase
9016 * of inflation, after all child views have been added.
9017 *
9018 * <p>Even if the subclass overrides onFinishInflate, they should always be
9019 * sure to call the super method, so that we get called.
9020 */
9021 protected void onFinishInflate() {
9022 }
9023
9024 /**
9025 * Returns the resources associated with this view.
9026 *
9027 * @return Resources object.
9028 */
9029 public Resources getResources() {
9030 return mResources;
9031 }
9032
9033 /**
9034 * Invalidates the specified Drawable.
9035 *
9036 * @param drawable the drawable to invalidate
9037 */
9038 public void invalidateDrawable(Drawable drawable) {
9039 if (verifyDrawable(drawable)) {
9040 final Rect dirty = drawable.getBounds();
9041 final int scrollX = mScrollX;
9042 final int scrollY = mScrollY;
9043
9044 invalidate(dirty.left + scrollX, dirty.top + scrollY,
9045 dirty.right + scrollX, dirty.bottom + scrollY);
9046 }
9047 }
9048
9049 /**
9050 * Schedules an action on a drawable to occur at a specified time.
9051 *
9052 * @param who the recipient of the action
9053 * @param what the action to run on the drawable
9054 * @param when the time at which the action must occur. Uses the
9055 * {@link SystemClock#uptimeMillis} timebase.
9056 */
9057 public void scheduleDrawable(Drawable who, Runnable what, long when) {
9058 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9059 mAttachInfo.mHandler.postAtTime(what, who, when);
9060 }
9061 }
9062
9063 /**
9064 * Cancels a scheduled action on a drawable.
9065 *
9066 * @param who the recipient of the action
9067 * @param what the action to cancel
9068 */
9069 public void unscheduleDrawable(Drawable who, Runnable what) {
9070 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9071 mAttachInfo.mHandler.removeCallbacks(what, who);
9072 }
9073 }
9074
9075 /**
9076 * Unschedule any events associated with the given Drawable. This can be
9077 * used when selecting a new Drawable into a view, so that the previous
9078 * one is completely unscheduled.
9079 *
9080 * @param who The Drawable to unschedule.
9081 *
9082 * @see #drawableStateChanged
9083 */
9084 public void unscheduleDrawable(Drawable who) {
9085 if (mAttachInfo != null) {
9086 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
9087 }
9088 }
9089
9090 /**
9091 * If your view subclass is displaying its own Drawable objects, it should
9092 * override this function and return true for any Drawable it is
9093 * displaying. This allows animations for those drawables to be
9094 * scheduled.
9095 *
9096 * <p>Be sure to call through to the super class when overriding this
9097 * function.
9098 *
9099 * @param who The Drawable to verify. Return true if it is one you are
9100 * displaying, else return the result of calling through to the
9101 * super class.
9102 *
9103 * @return boolean If true than the Drawable is being displayed in the
9104 * view; else false and it is not allowed to animate.
9105 *
9106 * @see #unscheduleDrawable
9107 * @see #drawableStateChanged
9108 */
9109 protected boolean verifyDrawable(Drawable who) {
9110 return who == mBGDrawable;
9111 }
9112
9113 /**
9114 * This function is called whenever the state of the view changes in such
9115 * a way that it impacts the state of drawables being shown.
9116 *
9117 * <p>Be sure to call through to the superclass when overriding this
9118 * function.
9119 *
9120 * @see Drawable#setState
9121 */
9122 protected void drawableStateChanged() {
9123 Drawable d = mBGDrawable;
9124 if (d != null && d.isStateful()) {
9125 d.setState(getDrawableState());
9126 }
9127 }
9128
9129 /**
9130 * Call this to force a view to update its drawable state. This will cause
9131 * drawableStateChanged to be called on this view. Views that are interested
9132 * in the new state should call getDrawableState.
9133 *
9134 * @see #drawableStateChanged
9135 * @see #getDrawableState
9136 */
9137 public void refreshDrawableState() {
9138 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9139 drawableStateChanged();
9140
9141 ViewParent parent = mParent;
9142 if (parent != null) {
9143 parent.childDrawableStateChanged(this);
9144 }
9145 }
9146
9147 /**
9148 * Return an array of resource IDs of the drawable states representing the
9149 * current state of the view.
9150 *
9151 * @return The current drawable state
9152 *
9153 * @see Drawable#setState
9154 * @see #drawableStateChanged
9155 * @see #onCreateDrawableState
9156 */
9157 public final int[] getDrawableState() {
9158 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
9159 return mDrawableState;
9160 } else {
9161 mDrawableState = onCreateDrawableState(0);
9162 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
9163 return mDrawableState;
9164 }
9165 }
9166
9167 /**
9168 * Generate the new {@link android.graphics.drawable.Drawable} state for
9169 * this view. This is called by the view
9170 * system when the cached Drawable state is determined to be invalid. To
9171 * retrieve the current state, you should use {@link #getDrawableState}.
9172 *
9173 * @param extraSpace if non-zero, this is the number of extra entries you
9174 * would like in the returned array in which you can place your own
9175 * states.
9176 *
9177 * @return Returns an array holding the current {@link Drawable} state of
9178 * the view.
9179 *
9180 * @see #mergeDrawableStates
9181 */
9182 protected int[] onCreateDrawableState(int extraSpace) {
9183 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
9184 mParent instanceof View) {
9185 return ((View) mParent).onCreateDrawableState(extraSpace);
9186 }
9187
9188 int[] drawableState;
9189
9190 int privateFlags = mPrivateFlags;
9191
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009192 int viewStateIndex = 0;
9193 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
9194 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
9195 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07009196 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009197 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
9198 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08009199 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
9200 // This is set if HW acceleration is requested, even if the current
9201 // process doesn't allow it. This is just to allow app preview
9202 // windows to better match their app.
9203 viewStateIndex |= VIEW_STATE_ACCELERATED;
9204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009205
9206 drawableState = VIEW_STATE_SETS[viewStateIndex];
9207
9208 //noinspection ConstantIfStatement
9209 if (false) {
9210 Log.i("View", "drawableStateIndex=" + viewStateIndex);
9211 Log.i("View", toString()
9212 + " pressed=" + ((privateFlags & PRESSED) != 0)
9213 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
9214 + " fo=" + hasFocus()
9215 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009216 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009217 + ": " + Arrays.toString(drawableState));
9218 }
9219
9220 if (extraSpace == 0) {
9221 return drawableState;
9222 }
9223
9224 final int[] fullState;
9225 if (drawableState != null) {
9226 fullState = new int[drawableState.length + extraSpace];
9227 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
9228 } else {
9229 fullState = new int[extraSpace];
9230 }
9231
9232 return fullState;
9233 }
9234
9235 /**
9236 * Merge your own state values in <var>additionalState</var> into the base
9237 * state values <var>baseState</var> that were returned by
9238 * {@link #onCreateDrawableState}.
9239 *
9240 * @param baseState The base state values returned by
9241 * {@link #onCreateDrawableState}, which will be modified to also hold your
9242 * own additional state values.
9243 *
9244 * @param additionalState The additional state values you would like
9245 * added to <var>baseState</var>; this array is not modified.
9246 *
9247 * @return As a convenience, the <var>baseState</var> array you originally
9248 * passed into the function is returned.
9249 *
9250 * @see #onCreateDrawableState
9251 */
9252 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
9253 final int N = baseState.length;
9254 int i = N - 1;
9255 while (i >= 0 && baseState[i] == 0) {
9256 i--;
9257 }
9258 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
9259 return baseState;
9260 }
9261
9262 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07009263 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
9264 * on all Drawable objects associated with this view.
9265 */
9266 public void jumpDrawablesToCurrentState() {
9267 if (mBGDrawable != null) {
9268 mBGDrawable.jumpToCurrentState();
9269 }
9270 }
9271
9272 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009273 * Sets the background color for this view.
9274 * @param color the color of the background
9275 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009276 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009277 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07009278 if (mBGDrawable instanceof ColorDrawable) {
9279 ((ColorDrawable) mBGDrawable).setColor(color);
9280 } else {
9281 setBackgroundDrawable(new ColorDrawable(color));
9282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009283 }
9284
9285 /**
9286 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07009287 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009288 * @param resid The identifier of the resource.
9289 * @attr ref android.R.styleable#View_background
9290 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009291 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009292 public void setBackgroundResource(int resid) {
9293 if (resid != 0 && resid == mBackgroundResource) {
9294 return;
9295 }
9296
9297 Drawable d= null;
9298 if (resid != 0) {
9299 d = mResources.getDrawable(resid);
9300 }
9301 setBackgroundDrawable(d);
9302
9303 mBackgroundResource = resid;
9304 }
9305
9306 /**
9307 * Set the background to a given Drawable, or remove the background. If the
9308 * background has padding, this View's padding is set to the background's
9309 * padding. However, when a background is removed, this View's padding isn't
9310 * touched. If setting the padding is desired, please use
9311 * {@link #setPadding(int, int, int, int)}.
9312 *
9313 * @param d The Drawable to use as the background, or null to remove the
9314 * background
9315 */
9316 public void setBackgroundDrawable(Drawable d) {
9317 boolean requestLayout = false;
9318
9319 mBackgroundResource = 0;
9320
9321 /*
9322 * Regardless of whether we're setting a new background or not, we want
9323 * to clear the previous drawable.
9324 */
9325 if (mBGDrawable != null) {
9326 mBGDrawable.setCallback(null);
9327 unscheduleDrawable(mBGDrawable);
9328 }
9329
9330 if (d != null) {
9331 Rect padding = sThreadLocal.get();
9332 if (padding == null) {
9333 padding = new Rect();
9334 sThreadLocal.set(padding);
9335 }
9336 if (d.getPadding(padding)) {
9337 setPadding(padding.left, padding.top, padding.right, padding.bottom);
9338 }
9339
9340 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
9341 // if it has a different minimum size, we should layout again
9342 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
9343 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
9344 requestLayout = true;
9345 }
9346
9347 d.setCallback(this);
9348 if (d.isStateful()) {
9349 d.setState(getDrawableState());
9350 }
9351 d.setVisible(getVisibility() == VISIBLE, false);
9352 mBGDrawable = d;
9353
9354 if ((mPrivateFlags & SKIP_DRAW) != 0) {
9355 mPrivateFlags &= ~SKIP_DRAW;
9356 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
9357 requestLayout = true;
9358 }
9359 } else {
9360 /* Remove the background */
9361 mBGDrawable = null;
9362
9363 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
9364 /*
9365 * This view ONLY drew the background before and we're removing
9366 * the background, so now it won't draw anything
9367 * (hence we SKIP_DRAW)
9368 */
9369 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
9370 mPrivateFlags |= SKIP_DRAW;
9371 }
9372
9373 /*
9374 * When the background is set, we try to apply its padding to this
9375 * View. When the background is removed, we don't touch this View's
9376 * padding. This is noted in the Javadocs. Hence, we don't need to
9377 * requestLayout(), the invalidate() below is sufficient.
9378 */
9379
9380 // The old background's minimum size could have affected this
9381 // View's layout, so let's requestLayout
9382 requestLayout = true;
9383 }
9384
Romain Guy8f1344f52009-05-15 16:03:59 -07009385 computeOpaqueFlags();
9386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009387 if (requestLayout) {
9388 requestLayout();
9389 }
9390
9391 mBackgroundSizeChanged = true;
9392 invalidate();
9393 }
9394
9395 /**
9396 * Gets the background drawable
9397 * @return The drawable used as the background for this view, if any.
9398 */
9399 public Drawable getBackground() {
9400 return mBGDrawable;
9401 }
9402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009403 /**
9404 * Sets the padding. The view may add on the space required to display
9405 * the scrollbars, depending on the style and visibility of the scrollbars.
9406 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
9407 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
9408 * from the values set in this call.
9409 *
9410 * @attr ref android.R.styleable#View_padding
9411 * @attr ref android.R.styleable#View_paddingBottom
9412 * @attr ref android.R.styleable#View_paddingLeft
9413 * @attr ref android.R.styleable#View_paddingRight
9414 * @attr ref android.R.styleable#View_paddingTop
9415 * @param left the left padding in pixels
9416 * @param top the top padding in pixels
9417 * @param right the right padding in pixels
9418 * @param bottom the bottom padding in pixels
9419 */
9420 public void setPadding(int left, int top, int right, int bottom) {
9421 boolean changed = false;
9422
Adam Powell20232d02010-12-08 21:08:53 -08009423 mUserPaddingLeft = left;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009424 mUserPaddingRight = right;
9425 mUserPaddingBottom = bottom;
9426
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009427 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07009428
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009429 // Common case is there are no scroll bars.
9430 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009431 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
Adam Powell20232d02010-12-08 21:08:53 -08009432 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
9433 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009434 ? 0 : getVerticalScrollbarWidth();
Adam Powell20232d02010-12-08 21:08:53 -08009435 switch (mVerticalScrollbarPosition) {
9436 case SCROLLBAR_POSITION_DEFAULT:
9437 case SCROLLBAR_POSITION_RIGHT:
9438 right += offset;
9439 break;
9440 case SCROLLBAR_POSITION_LEFT:
9441 left += offset;
9442 break;
9443 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009444 }
Adam Powell20232d02010-12-08 21:08:53 -08009445 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009446 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9447 ? 0 : getHorizontalScrollbarHeight();
9448 }
9449 }
Romain Guy8506ab42009-06-11 17:35:47 -07009450
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009451 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009452 changed = true;
9453 mPaddingLeft = left;
9454 }
9455 if (mPaddingTop != top) {
9456 changed = true;
9457 mPaddingTop = top;
9458 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009459 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009460 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009461 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009462 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009463 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009464 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009465 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009466 }
9467
9468 if (changed) {
9469 requestLayout();
9470 }
9471 }
9472
9473 /**
9474 * Returns the top padding of this view.
9475 *
9476 * @return the top padding in pixels
9477 */
9478 public int getPaddingTop() {
9479 return mPaddingTop;
9480 }
9481
9482 /**
9483 * Returns the bottom padding of this view. If there are inset and enabled
9484 * scrollbars, this value may include the space required to display the
9485 * scrollbars as well.
9486 *
9487 * @return the bottom padding in pixels
9488 */
9489 public int getPaddingBottom() {
9490 return mPaddingBottom;
9491 }
9492
9493 /**
9494 * Returns the left padding of this view. If there are inset and enabled
9495 * scrollbars, this value may include the space required to display the
9496 * scrollbars as well.
9497 *
9498 * @return the left padding in pixels
9499 */
9500 public int getPaddingLeft() {
9501 return mPaddingLeft;
9502 }
9503
9504 /**
9505 * Returns the right padding of this view. If there are inset and enabled
9506 * scrollbars, this value may include the space required to display the
9507 * scrollbars as well.
9508 *
9509 * @return the right padding in pixels
9510 */
9511 public int getPaddingRight() {
9512 return mPaddingRight;
9513 }
9514
9515 /**
9516 * Changes the selection state of this view. A view can be selected or not.
9517 * Note that selection is not the same as focus. Views are typically
9518 * selected in the context of an AdapterView like ListView or GridView;
9519 * the selected view is the view that is highlighted.
9520 *
9521 * @param selected true if the view must be selected, false otherwise
9522 */
9523 public void setSelected(boolean selected) {
9524 if (((mPrivateFlags & SELECTED) != 0) != selected) {
9525 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07009526 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009527 invalidate();
9528 refreshDrawableState();
9529 dispatchSetSelected(selected);
9530 }
9531 }
9532
9533 /**
9534 * Dispatch setSelected to all of this View's children.
9535 *
9536 * @see #setSelected(boolean)
9537 *
9538 * @param selected The new selected state
9539 */
9540 protected void dispatchSetSelected(boolean selected) {
9541 }
9542
9543 /**
9544 * Indicates the selection state of this view.
9545 *
9546 * @return true if the view is selected, false otherwise
9547 */
9548 @ViewDebug.ExportedProperty
9549 public boolean isSelected() {
9550 return (mPrivateFlags & SELECTED) != 0;
9551 }
9552
9553 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009554 * Changes the activated state of this view. A view can be activated or not.
9555 * Note that activation is not the same as selection. Selection is
9556 * a transient property, representing the view (hierarchy) the user is
9557 * currently interacting with. Activation is a longer-term state that the
9558 * user can move views in and out of. For example, in a list view with
9559 * single or multiple selection enabled, the views in the current selection
9560 * set are activated. (Um, yeah, we are deeply sorry about the terminology
9561 * here.) The activated state is propagated down to children of the view it
9562 * is set on.
9563 *
9564 * @param activated true if the view must be activated, false otherwise
9565 */
9566 public void setActivated(boolean activated) {
9567 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9568 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
9569 invalidate();
9570 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07009571 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009572 }
9573 }
9574
9575 /**
9576 * Dispatch setActivated to all of this View's children.
9577 *
9578 * @see #setActivated(boolean)
9579 *
9580 * @param activated The new activated state
9581 */
9582 protected void dispatchSetActivated(boolean activated) {
9583 }
9584
9585 /**
9586 * Indicates the activation state of this view.
9587 *
9588 * @return true if the view is activated, false otherwise
9589 */
9590 @ViewDebug.ExportedProperty
9591 public boolean isActivated() {
9592 return (mPrivateFlags & ACTIVATED) != 0;
9593 }
9594
9595 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009596 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9597 * observer can be used to get notifications when global events, like
9598 * layout, happen.
9599 *
9600 * The returned ViewTreeObserver observer is not guaranteed to remain
9601 * valid for the lifetime of this View. If the caller of this method keeps
9602 * a long-lived reference to ViewTreeObserver, it should always check for
9603 * the return value of {@link ViewTreeObserver#isAlive()}.
9604 *
9605 * @return The ViewTreeObserver for this view's hierarchy.
9606 */
9607 public ViewTreeObserver getViewTreeObserver() {
9608 if (mAttachInfo != null) {
9609 return mAttachInfo.mTreeObserver;
9610 }
9611 if (mFloatingTreeObserver == null) {
9612 mFloatingTreeObserver = new ViewTreeObserver();
9613 }
9614 return mFloatingTreeObserver;
9615 }
9616
9617 /**
9618 * <p>Finds the topmost view in the current view hierarchy.</p>
9619 *
9620 * @return the topmost view containing this view
9621 */
9622 public View getRootView() {
9623 if (mAttachInfo != null) {
9624 final View v = mAttachInfo.mRootView;
9625 if (v != null) {
9626 return v;
9627 }
9628 }
Romain Guy8506ab42009-06-11 17:35:47 -07009629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009630 View parent = this;
9631
9632 while (parent.mParent != null && parent.mParent instanceof View) {
9633 parent = (View) parent.mParent;
9634 }
9635
9636 return parent;
9637 }
9638
9639 /**
9640 * <p>Computes the coordinates of this view on the screen. The argument
9641 * must be an array of two integers. After the method returns, the array
9642 * contains the x and y location in that order.</p>
9643 *
9644 * @param location an array of two integers in which to hold the coordinates
9645 */
9646 public void getLocationOnScreen(int[] location) {
9647 getLocationInWindow(location);
9648
9649 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009650 if (info != null) {
9651 location[0] += info.mWindowLeft;
9652 location[1] += info.mWindowTop;
9653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009654 }
9655
9656 /**
9657 * <p>Computes the coordinates of this view in its window. The argument
9658 * must be an array of two integers. After the method returns, the array
9659 * contains the x and y location in that order.</p>
9660 *
9661 * @param location an array of two integers in which to hold the coordinates
9662 */
9663 public void getLocationInWindow(int[] location) {
9664 if (location == null || location.length < 2) {
9665 throw new IllegalArgumentException("location must be an array of "
9666 + "two integers");
9667 }
9668
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009669 location[0] = mLeft + (int) (mTranslationX + 0.5f);
9670 location[1] = mTop + (int) (mTranslationY + 0.5f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009671
9672 ViewParent viewParent = mParent;
9673 while (viewParent instanceof View) {
9674 final View view = (View)viewParent;
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009675 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
9676 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009677 viewParent = view.mParent;
9678 }
Romain Guy8506ab42009-06-11 17:35:47 -07009679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009680 if (viewParent instanceof ViewRoot) {
9681 // *cough*
9682 final ViewRoot vr = (ViewRoot)viewParent;
9683 location[1] -= vr.mCurScrollY;
9684 }
9685 }
9686
9687 /**
9688 * {@hide}
9689 * @param id the id of the view to be found
9690 * @return the view of the specified id, null if cannot be found
9691 */
9692 protected View findViewTraversal(int id) {
9693 if (id == mID) {
9694 return this;
9695 }
9696 return null;
9697 }
9698
9699 /**
9700 * {@hide}
9701 * @param tag the tag of the view to be found
9702 * @return the view of specified tag, null if cannot be found
9703 */
9704 protected View findViewWithTagTraversal(Object tag) {
9705 if (tag != null && tag.equals(mTag)) {
9706 return this;
9707 }
9708 return null;
9709 }
9710
9711 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009712 * {@hide}
9713 * @param predicate The predicate to evaluate.
9714 * @return The first view that matches the predicate or null.
9715 */
9716 protected View findViewByPredicateTraversal(Predicate<View> predicate) {
9717 if (predicate.apply(this)) {
9718 return this;
9719 }
9720 return null;
9721 }
9722
9723 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009724 * Look for a child view with the given id. If this view has the given
9725 * id, return this view.
9726 *
9727 * @param id The id to search for.
9728 * @return The view that has the given id in the hierarchy or null
9729 */
9730 public final View findViewById(int id) {
9731 if (id < 0) {
9732 return null;
9733 }
9734 return findViewTraversal(id);
9735 }
9736
9737 /**
9738 * Look for a child view with the given tag. If this view has the given
9739 * tag, return this view.
9740 *
9741 * @param tag The tag to search for, using "tag.equals(getTag())".
9742 * @return The View that has the given tag in the hierarchy or null
9743 */
9744 public final View findViewWithTag(Object tag) {
9745 if (tag == null) {
9746 return null;
9747 }
9748 return findViewWithTagTraversal(tag);
9749 }
9750
9751 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009752 * {@hide}
9753 * Look for a child view that matches the specified predicate.
9754 * If this view matches the predicate, return this view.
9755 *
9756 * @param predicate The predicate to evaluate.
9757 * @return The first view that matches the predicate or null.
9758 */
9759 public final View findViewByPredicate(Predicate<View> predicate) {
9760 return findViewByPredicateTraversal(predicate);
9761 }
9762
9763 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009764 * Sets the identifier for this view. The identifier does not have to be
9765 * unique in this view's hierarchy. The identifier should be a positive
9766 * number.
9767 *
9768 * @see #NO_ID
9769 * @see #getId
9770 * @see #findViewById
9771 *
9772 * @param id a number used to identify the view
9773 *
9774 * @attr ref android.R.styleable#View_id
9775 */
9776 public void setId(int id) {
9777 mID = id;
9778 }
9779
9780 /**
9781 * {@hide}
9782 *
9783 * @param isRoot true if the view belongs to the root namespace, false
9784 * otherwise
9785 */
9786 public void setIsRootNamespace(boolean isRoot) {
9787 if (isRoot) {
9788 mPrivateFlags |= IS_ROOT_NAMESPACE;
9789 } else {
9790 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9791 }
9792 }
9793
9794 /**
9795 * {@hide}
9796 *
9797 * @return true if the view belongs to the root namespace, false otherwise
9798 */
9799 public boolean isRootNamespace() {
9800 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9801 }
9802
9803 /**
9804 * Returns this view's identifier.
9805 *
9806 * @return a positive integer used to identify the view or {@link #NO_ID}
9807 * if the view has no ID
9808 *
9809 * @see #setId
9810 * @see #findViewById
9811 * @attr ref android.R.styleable#View_id
9812 */
9813 @ViewDebug.CapturedViewProperty
9814 public int getId() {
9815 return mID;
9816 }
9817
9818 /**
9819 * Returns this view's tag.
9820 *
9821 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07009822 *
9823 * @see #setTag(Object)
9824 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009825 */
9826 @ViewDebug.ExportedProperty
9827 public Object getTag() {
9828 return mTag;
9829 }
9830
9831 /**
9832 * Sets the tag associated with this view. A tag can be used to mark
9833 * a view in its hierarchy and does not have to be unique within the
9834 * hierarchy. Tags can also be used to store data within a view without
9835 * resorting to another data structure.
9836 *
9837 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07009838 *
9839 * @see #getTag()
9840 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009841 */
9842 public void setTag(final Object tag) {
9843 mTag = tag;
9844 }
9845
9846 /**
Romain Guyd90a3312009-05-06 14:54:28 -07009847 * Returns the tag associated with this view and the specified key.
9848 *
9849 * @param key The key identifying the tag
9850 *
9851 * @return the Object stored in this view as a tag
9852 *
9853 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07009854 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07009855 */
9856 public Object getTag(int key) {
9857 SparseArray<Object> tags = null;
9858 synchronized (sTagsLock) {
9859 if (sTags != null) {
9860 tags = sTags.get(this);
9861 }
9862 }
9863
9864 if (tags != null) return tags.get(key);
9865 return null;
9866 }
9867
9868 /**
9869 * Sets a tag associated with this view and a key. A tag can be used
9870 * to mark a view in its hierarchy and does not have to be unique within
9871 * the hierarchy. Tags can also be used to store data within a view
9872 * without resorting to another data structure.
9873 *
9874 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07009875 * application to ensure it is unique (see the <a
9876 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9877 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07009878 * the Android framework or not associated with any package will cause
9879 * an {@link IllegalArgumentException} to be thrown.
9880 *
9881 * @param key The key identifying the tag
9882 * @param tag An Object to tag the view with
9883 *
9884 * @throws IllegalArgumentException If they specified key is not valid
9885 *
9886 * @see #setTag(Object)
9887 * @see #getTag(int)
9888 */
9889 public void setTag(int key, final Object tag) {
9890 // If the package id is 0x00 or 0x01, it's either an undefined package
9891 // or a framework id
9892 if ((key >>> 24) < 2) {
9893 throw new IllegalArgumentException("The key must be an application-specific "
9894 + "resource id.");
9895 }
9896
9897 setTagInternal(this, key, tag);
9898 }
9899
9900 /**
9901 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9902 * framework id.
9903 *
9904 * @hide
9905 */
9906 public void setTagInternal(int key, Object tag) {
9907 if ((key >>> 24) != 0x1) {
9908 throw new IllegalArgumentException("The key must be a framework-specific "
9909 + "resource id.");
9910 }
9911
Romain Guy8506ab42009-06-11 17:35:47 -07009912 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07009913 }
9914
9915 private static void setTagInternal(View view, int key, Object tag) {
9916 SparseArray<Object> tags = null;
9917 synchronized (sTagsLock) {
9918 if (sTags == null) {
9919 sTags = new WeakHashMap<View, SparseArray<Object>>();
9920 } else {
9921 tags = sTags.get(view);
9922 }
9923 }
9924
9925 if (tags == null) {
9926 tags = new SparseArray<Object>(2);
9927 synchronized (sTagsLock) {
9928 sTags.put(view, tags);
9929 }
9930 }
9931
9932 tags.put(key, tag);
9933 }
9934
9935 /**
Romain Guy13922e02009-05-12 17:56:14 -07009936 * @param consistency The type of consistency. See ViewDebug for more information.
9937 *
9938 * @hide
9939 */
9940 protected boolean dispatchConsistencyCheck(int consistency) {
9941 return onConsistencyCheck(consistency);
9942 }
9943
9944 /**
9945 * Method that subclasses should implement to check their consistency. The type of
9946 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07009947 *
Romain Guy13922e02009-05-12 17:56:14 -07009948 * @param consistency The type of consistency. See ViewDebug for more information.
9949 *
9950 * @throws IllegalStateException if the view is in an inconsistent state.
9951 *
9952 * @hide
9953 */
9954 protected boolean onConsistencyCheck(int consistency) {
9955 boolean result = true;
9956
9957 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9958 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9959
9960 if (checkLayout) {
9961 if (getParent() == null) {
9962 result = false;
9963 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9964 "View " + this + " does not have a parent.");
9965 }
9966
9967 if (mAttachInfo == null) {
9968 result = false;
9969 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9970 "View " + this + " is not attached to a window.");
9971 }
9972 }
9973
9974 if (checkDrawing) {
9975 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9976 // from their draw() method
9977
9978 if ((mPrivateFlags & DRAWN) != DRAWN &&
9979 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9980 result = false;
9981 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9982 "View " + this + " was invalidated but its drawing cache is valid.");
9983 }
9984 }
9985
9986 return result;
9987 }
9988
9989 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009990 * Prints information about this view in the log output, with the tag
9991 * {@link #VIEW_LOG_TAG}.
9992 *
9993 * @hide
9994 */
9995 public void debug() {
9996 debug(0);
9997 }
9998
9999 /**
10000 * Prints information about this view in the log output, with the tag
10001 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
10002 * indentation defined by the <code>depth</code>.
10003 *
10004 * @param depth the indentation level
10005 *
10006 * @hide
10007 */
10008 protected void debug(int depth) {
10009 String output = debugIndent(depth - 1);
10010
10011 output += "+ " + this;
10012 int id = getId();
10013 if (id != -1) {
10014 output += " (id=" + id + ")";
10015 }
10016 Object tag = getTag();
10017 if (tag != null) {
10018 output += " (tag=" + tag + ")";
10019 }
10020 Log.d(VIEW_LOG_TAG, output);
10021
10022 if ((mPrivateFlags & FOCUSED) != 0) {
10023 output = debugIndent(depth) + " FOCUSED";
10024 Log.d(VIEW_LOG_TAG, output);
10025 }
10026
10027 output = debugIndent(depth);
10028 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
10029 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
10030 + "} ";
10031 Log.d(VIEW_LOG_TAG, output);
10032
10033 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
10034 || mPaddingBottom != 0) {
10035 output = debugIndent(depth);
10036 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
10037 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
10038 Log.d(VIEW_LOG_TAG, output);
10039 }
10040
10041 output = debugIndent(depth);
10042 output += "mMeasureWidth=" + mMeasuredWidth +
10043 " mMeasureHeight=" + mMeasuredHeight;
10044 Log.d(VIEW_LOG_TAG, output);
10045
10046 output = debugIndent(depth);
10047 if (mLayoutParams == null) {
10048 output += "BAD! no layout params";
10049 } else {
10050 output = mLayoutParams.debug(output);
10051 }
10052 Log.d(VIEW_LOG_TAG, output);
10053
10054 output = debugIndent(depth);
10055 output += "flags={";
10056 output += View.printFlags(mViewFlags);
10057 output += "}";
10058 Log.d(VIEW_LOG_TAG, output);
10059
10060 output = debugIndent(depth);
10061 output += "privateFlags={";
10062 output += View.printPrivateFlags(mPrivateFlags);
10063 output += "}";
10064 Log.d(VIEW_LOG_TAG, output);
10065 }
10066
10067 /**
10068 * Creates an string of whitespaces used for indentation.
10069 *
10070 * @param depth the indentation level
10071 * @return a String containing (depth * 2 + 3) * 2 white spaces
10072 *
10073 * @hide
10074 */
10075 protected static String debugIndent(int depth) {
10076 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
10077 for (int i = 0; i < (depth * 2) + 3; i++) {
10078 spaces.append(' ').append(' ');
10079 }
10080 return spaces.toString();
10081 }
10082
10083 /**
10084 * <p>Return the offset of the widget's text baseline from the widget's top
10085 * boundary. If this widget does not support baseline alignment, this
10086 * method returns -1. </p>
10087 *
10088 * @return the offset of the baseline within the widget's bounds or -1
10089 * if baseline alignment is not supported
10090 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -070010091 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010092 public int getBaseline() {
10093 return -1;
10094 }
10095
10096 /**
10097 * Call this when something has changed which has invalidated the
10098 * layout of this view. This will schedule a layout pass of the view
10099 * tree.
10100 */
10101 public void requestLayout() {
10102 if (ViewDebug.TRACE_HIERARCHY) {
10103 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
10104 }
10105
10106 mPrivateFlags |= FORCE_LAYOUT;
10107
10108 if (mParent != null && !mParent.isLayoutRequested()) {
10109 mParent.requestLayout();
10110 }
10111 }
10112
10113 /**
10114 * Forces this view to be laid out during the next layout pass.
10115 * This method does not call requestLayout() or forceLayout()
10116 * on the parent.
10117 */
10118 public void forceLayout() {
10119 mPrivateFlags |= FORCE_LAYOUT;
10120 }
10121
10122 /**
10123 * <p>
10124 * This is called to find out how big a view should be. The parent
10125 * supplies constraint information in the width and height parameters.
10126 * </p>
10127 *
10128 * <p>
10129 * The actual mesurement work of a view is performed in
10130 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
10131 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
10132 * </p>
10133 *
10134 *
10135 * @param widthMeasureSpec Horizontal space requirements as imposed by the
10136 * parent
10137 * @param heightMeasureSpec Vertical space requirements as imposed by the
10138 * parent
10139 *
10140 * @see #onMeasure(int, int)
10141 */
10142 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
10143 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
10144 widthMeasureSpec != mOldWidthMeasureSpec ||
10145 heightMeasureSpec != mOldHeightMeasureSpec) {
10146
10147 // first clears the measured dimension flag
10148 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
10149
10150 if (ViewDebug.TRACE_HIERARCHY) {
10151 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
10152 }
10153
10154 // measure ourselves, this should set the measured dimension flag back
10155 onMeasure(widthMeasureSpec, heightMeasureSpec);
10156
10157 // flag not set, setMeasuredDimension() was not invoked, we raise
10158 // an exception to warn the developer
10159 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
10160 throw new IllegalStateException("onMeasure() did not set the"
10161 + " measured dimension by calling"
10162 + " setMeasuredDimension()");
10163 }
10164
10165 mPrivateFlags |= LAYOUT_REQUIRED;
10166 }
10167
10168 mOldWidthMeasureSpec = widthMeasureSpec;
10169 mOldHeightMeasureSpec = heightMeasureSpec;
10170 }
10171
10172 /**
10173 * <p>
10174 * Measure the view and its content to determine the measured width and the
10175 * measured height. This method is invoked by {@link #measure(int, int)} and
10176 * should be overriden by subclasses to provide accurate and efficient
10177 * measurement of their contents.
10178 * </p>
10179 *
10180 * <p>
10181 * <strong>CONTRACT:</strong> When overriding this method, you
10182 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
10183 * measured width and height of this view. Failure to do so will trigger an
10184 * <code>IllegalStateException</code>, thrown by
10185 * {@link #measure(int, int)}. Calling the superclass'
10186 * {@link #onMeasure(int, int)} is a valid use.
10187 * </p>
10188 *
10189 * <p>
10190 * The base class implementation of measure defaults to the background size,
10191 * unless a larger size is allowed by the MeasureSpec. Subclasses should
10192 * override {@link #onMeasure(int, int)} to provide better measurements of
10193 * their content.
10194 * </p>
10195 *
10196 * <p>
10197 * If this method is overridden, it is the subclass's responsibility to make
10198 * sure the measured height and width are at least the view's minimum height
10199 * and width ({@link #getSuggestedMinimumHeight()} and
10200 * {@link #getSuggestedMinimumWidth()}).
10201 * </p>
10202 *
10203 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
10204 * The requirements are encoded with
10205 * {@link android.view.View.MeasureSpec}.
10206 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
10207 * The requirements are encoded with
10208 * {@link android.view.View.MeasureSpec}.
10209 *
10210 * @see #getMeasuredWidth()
10211 * @see #getMeasuredHeight()
10212 * @see #setMeasuredDimension(int, int)
10213 * @see #getSuggestedMinimumHeight()
10214 * @see #getSuggestedMinimumWidth()
10215 * @see android.view.View.MeasureSpec#getMode(int)
10216 * @see android.view.View.MeasureSpec#getSize(int)
10217 */
10218 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
10219 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
10220 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
10221 }
10222
10223 /**
10224 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
10225 * measured width and measured height. Failing to do so will trigger an
10226 * exception at measurement time.</p>
10227 *
Dianne Hackborn189ee182010-12-02 21:48:53 -080010228 * @param measuredWidth The measured width of this view. May be a complex
10229 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10230 * {@link #MEASURED_STATE_TOO_SMALL}.
10231 * @param measuredHeight The measured height of this view. May be a complex
10232 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10233 * {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010234 */
10235 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
10236 mMeasuredWidth = measuredWidth;
10237 mMeasuredHeight = measuredHeight;
10238
10239 mPrivateFlags |= MEASURED_DIMENSION_SET;
10240 }
10241
10242 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -080010243 * Merge two states as returned by {@link #getMeasuredState()}.
10244 * @param curState The current state as returned from a view or the result
10245 * of combining multiple views.
10246 * @param newState The new view state to combine.
10247 * @return Returns a new integer reflecting the combination of the two
10248 * states.
10249 */
10250 public static int combineMeasuredStates(int curState, int newState) {
10251 return curState | newState;
10252 }
10253
10254 /**
10255 * Version of {@link #resolveSizeAndState(int, int, int)}
10256 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
10257 */
10258 public static int resolveSize(int size, int measureSpec) {
10259 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
10260 }
10261
10262 /**
10263 * Utility to reconcile a desired size and state, with constraints imposed
10264 * by a MeasureSpec. Will take the desired size, unless a different size
10265 * is imposed by the constraints. The returned value is a compound integer,
10266 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
10267 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
10268 * size is smaller than the size the view wants to be.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010269 *
10270 * @param size How big the view wants to be
10271 * @param measureSpec Constraints imposed by the parent
Dianne Hackborn189ee182010-12-02 21:48:53 -080010272 * @return Size information bit mask as defined by
10273 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010274 */
Dianne Hackborn189ee182010-12-02 21:48:53 -080010275 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010276 int result = size;
10277 int specMode = MeasureSpec.getMode(measureSpec);
10278 int specSize = MeasureSpec.getSize(measureSpec);
10279 switch (specMode) {
10280 case MeasureSpec.UNSPECIFIED:
10281 result = size;
10282 break;
10283 case MeasureSpec.AT_MOST:
Dianne Hackborn189ee182010-12-02 21:48:53 -080010284 if (specSize < size) {
10285 result = specSize | MEASURED_STATE_TOO_SMALL;
10286 } else {
10287 result = size;
10288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010289 break;
10290 case MeasureSpec.EXACTLY:
10291 result = specSize;
10292 break;
10293 }
Dianne Hackborn189ee182010-12-02 21:48:53 -080010294 return result | (childMeasuredState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010295 }
10296
10297 /**
10298 * Utility to return a default size. Uses the supplied size if the
10299 * MeasureSpec imposed no contraints. Will get larger if allowed
10300 * by the MeasureSpec.
10301 *
10302 * @param size Default size for this view
10303 * @param measureSpec Constraints imposed by the parent
10304 * @return The size this view should be.
10305 */
10306 public static int getDefaultSize(int size, int measureSpec) {
10307 int result = size;
10308 int specMode = MeasureSpec.getMode(measureSpec);
10309 int specSize = MeasureSpec.getSize(measureSpec);
10310
10311 switch (specMode) {
10312 case MeasureSpec.UNSPECIFIED:
10313 result = size;
10314 break;
10315 case MeasureSpec.AT_MOST:
10316 case MeasureSpec.EXACTLY:
10317 result = specSize;
10318 break;
10319 }
10320 return result;
10321 }
10322
10323 /**
10324 * Returns the suggested minimum height that the view should use. This
10325 * returns the maximum of the view's minimum height
10326 * and the background's minimum height
10327 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
10328 * <p>
10329 * When being used in {@link #onMeasure(int, int)}, the caller should still
10330 * ensure the returned height is within the requirements of the parent.
10331 *
10332 * @return The suggested minimum height of the view.
10333 */
10334 protected int getSuggestedMinimumHeight() {
10335 int suggestedMinHeight = mMinHeight;
10336
10337 if (mBGDrawable != null) {
10338 final int bgMinHeight = mBGDrawable.getMinimumHeight();
10339 if (suggestedMinHeight < bgMinHeight) {
10340 suggestedMinHeight = bgMinHeight;
10341 }
10342 }
10343
10344 return suggestedMinHeight;
10345 }
10346
10347 /**
10348 * Returns the suggested minimum width that the view should use. This
10349 * returns the maximum of the view's minimum width)
10350 * and the background's minimum width
10351 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
10352 * <p>
10353 * When being used in {@link #onMeasure(int, int)}, the caller should still
10354 * ensure the returned width is within the requirements of the parent.
10355 *
10356 * @return The suggested minimum width of the view.
10357 */
10358 protected int getSuggestedMinimumWidth() {
10359 int suggestedMinWidth = mMinWidth;
10360
10361 if (mBGDrawable != null) {
10362 final int bgMinWidth = mBGDrawable.getMinimumWidth();
10363 if (suggestedMinWidth < bgMinWidth) {
10364 suggestedMinWidth = bgMinWidth;
10365 }
10366 }
10367
10368 return suggestedMinWidth;
10369 }
10370
10371 /**
10372 * Sets the minimum height of the view. It is not guaranteed the view will
10373 * be able to achieve this minimum height (for example, if its parent layout
10374 * constrains it with less available height).
10375 *
10376 * @param minHeight The minimum height the view will try to be.
10377 */
10378 public void setMinimumHeight(int minHeight) {
10379 mMinHeight = minHeight;
10380 }
10381
10382 /**
10383 * Sets the minimum width of the view. It is not guaranteed the view will
10384 * be able to achieve this minimum width (for example, if its parent layout
10385 * constrains it with less available width).
10386 *
10387 * @param minWidth The minimum width the view will try to be.
10388 */
10389 public void setMinimumWidth(int minWidth) {
10390 mMinWidth = minWidth;
10391 }
10392
10393 /**
10394 * Get the animation currently associated with this view.
10395 *
10396 * @return The animation that is currently playing or
10397 * scheduled to play for this view.
10398 */
10399 public Animation getAnimation() {
10400 return mCurrentAnimation;
10401 }
10402
10403 /**
10404 * Start the specified animation now.
10405 *
10406 * @param animation the animation to start now
10407 */
10408 public void startAnimation(Animation animation) {
10409 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
10410 setAnimation(animation);
10411 invalidate();
10412 }
10413
10414 /**
10415 * Cancels any animations for this view.
10416 */
10417 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -080010418 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -080010419 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -080010420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010421 mCurrentAnimation = null;
10422 }
10423
10424 /**
10425 * Sets the next animation to play for this view.
10426 * If you want the animation to play immediately, use
10427 * startAnimation. This method provides allows fine-grained
10428 * control over the start time and invalidation, but you
10429 * must make sure that 1) the animation has a start time set, and
10430 * 2) the view will be invalidated when the animation is supposed to
10431 * start.
10432 *
10433 * @param animation The next animation, or null.
10434 */
10435 public void setAnimation(Animation animation) {
10436 mCurrentAnimation = animation;
10437 if (animation != null) {
10438 animation.reset();
10439 }
10440 }
10441
10442 /**
10443 * Invoked by a parent ViewGroup to notify the start of the animation
10444 * currently associated with this view. If you override this method,
10445 * always call super.onAnimationStart();
10446 *
10447 * @see #setAnimation(android.view.animation.Animation)
10448 * @see #getAnimation()
10449 */
10450 protected void onAnimationStart() {
10451 mPrivateFlags |= ANIMATION_STARTED;
10452 }
10453
10454 /**
10455 * Invoked by a parent ViewGroup to notify the end of the animation
10456 * currently associated with this view. If you override this method,
10457 * always call super.onAnimationEnd();
10458 *
10459 * @see #setAnimation(android.view.animation.Animation)
10460 * @see #getAnimation()
10461 */
10462 protected void onAnimationEnd() {
10463 mPrivateFlags &= ~ANIMATION_STARTED;
10464 }
10465
10466 /**
10467 * Invoked if there is a Transform that involves alpha. Subclass that can
10468 * draw themselves with the specified alpha should return true, and then
10469 * respect that alpha when their onDraw() is called. If this returns false
10470 * then the view may be redirected to draw into an offscreen buffer to
10471 * fulfill the request, which will look fine, but may be slower than if the
10472 * subclass handles it internally. The default implementation returns false.
10473 *
10474 * @param alpha The alpha (0..255) to apply to the view's drawing
10475 * @return true if the view can draw with the specified alpha.
10476 */
10477 protected boolean onSetAlpha(int alpha) {
10478 return false;
10479 }
10480
10481 /**
10482 * This is used by the RootView to perform an optimization when
10483 * the view hierarchy contains one or several SurfaceView.
10484 * SurfaceView is always considered transparent, but its children are not,
10485 * therefore all View objects remove themselves from the global transparent
10486 * region (passed as a parameter to this function).
10487 *
10488 * @param region The transparent region for this ViewRoot (window).
10489 *
10490 * @return Returns true if the effective visibility of the view at this
10491 * point is opaque, regardless of the transparent region; returns false
10492 * if it is possible for underlying windows to be seen behind the view.
10493 *
10494 * {@hide}
10495 */
10496 public boolean gatherTransparentRegion(Region region) {
10497 final AttachInfo attachInfo = mAttachInfo;
10498 if (region != null && attachInfo != null) {
10499 final int pflags = mPrivateFlags;
10500 if ((pflags & SKIP_DRAW) == 0) {
10501 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10502 // remove it from the transparent region.
10503 final int[] location = attachInfo.mTransparentLocation;
10504 getLocationInWindow(location);
10505 region.op(location[0], location[1], location[0] + mRight - mLeft,
10506 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10507 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10508 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10509 // exists, so we remove the background drawable's non-transparent
10510 // parts from this transparent region.
10511 applyDrawableToTransparentRegion(mBGDrawable, region);
10512 }
10513 }
10514 return true;
10515 }
10516
10517 /**
10518 * Play a sound effect for this view.
10519 *
10520 * <p>The framework will play sound effects for some built in actions, such as
10521 * clicking, but you may wish to play these effects in your widget,
10522 * for instance, for internal navigation.
10523 *
10524 * <p>The sound effect will only be played if sound effects are enabled by the user, and
10525 * {@link #isSoundEffectsEnabled()} is true.
10526 *
10527 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10528 */
10529 public void playSoundEffect(int soundConstant) {
10530 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10531 return;
10532 }
10533 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10534 }
10535
10536 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010537 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010538 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010539 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010540 *
10541 * <p>The framework will provide haptic feedback for some built in actions,
10542 * such as long presses, but you may wish to provide feedback for your
10543 * own widget.
10544 *
10545 * <p>The feedback will only be performed if
10546 * {@link #isHapticFeedbackEnabled()} is true.
10547 *
10548 * @param feedbackConstant One of the constants defined in
10549 * {@link HapticFeedbackConstants}
10550 */
10551 public boolean performHapticFeedback(int feedbackConstant) {
10552 return performHapticFeedback(feedbackConstant, 0);
10553 }
10554
10555 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010556 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010557 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010558 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010559 *
10560 * @param feedbackConstant One of the constants defined in
10561 * {@link HapticFeedbackConstants}
10562 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10563 */
10564 public boolean performHapticFeedback(int feedbackConstant, int flags) {
10565 if (mAttachInfo == null) {
10566 return false;
10567 }
Romain Guyf607bdc2010-09-10 19:20:06 -070010568 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -070010569 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010570 && !isHapticFeedbackEnabled()) {
10571 return false;
10572 }
Romain Guy812ccbe2010-06-01 14:07:24 -070010573 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10574 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010575 }
10576
10577 /**
Christopher Tate2c095f32010-10-04 14:13:40 -070010578 * !!! TODO: real docs
10579 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010580 * The base class implementation makes the shadow the same size and appearance
Christopher Tate2c095f32010-10-04 14:13:40 -070010581 * as the view itself, and positions it with its center at the touch point.
10582 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010583 public static class DragShadowBuilder {
Christopher Tatea0374192010-10-05 13:06:41 -070010584 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -070010585
10586 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010587 * Construct a shadow builder object for use with the given view.
Christopher Tate2c095f32010-10-04 14:13:40 -070010588 * @param view
10589 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010590 public DragShadowBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -070010591 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -070010592 }
10593
Chris Tate6b391282010-10-14 15:48:59 -070010594 final public View getView() {
10595 return mView.get();
10596 }
10597
Christopher Tate2c095f32010-10-04 14:13:40 -070010598 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010599 * Provide the draggable-shadow metrics for the operation: the dimensions of
10600 * the shadow image itself, and the point within that shadow that should
Christopher Tate2c095f32010-10-04 14:13:40 -070010601 * be centered under the touch location while dragging.
10602 * <p>
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010603 * The default implementation sets the dimensions of the shadow to be the
10604 * same as the dimensions of the View itself and centers the shadow under
Christopher Tate2c095f32010-10-04 14:13:40 -070010605 * the touch point.
10606 *
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010607 * @param shadowSize The application should set the {@code x} member of this
10608 * parameter to the desired shadow width, and the {@code y} member to
Christopher Tate2c095f32010-10-04 14:13:40 -070010609 * the desired height.
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010610 * @param shadowTouchPoint The application should set this point to be the
10611 * location within the shadow that should track directly underneath
Christopher Tate2c095f32010-10-04 14:13:40 -070010612 * the touch point on the screen during a drag.
10613 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010614 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -070010615 final View view = mView.get();
10616 if (view != null) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010617 shadowSize.set(view.getWidth(), view.getHeight());
10618 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
Christopher Tatea0374192010-10-05 13:06:41 -070010619 } else {
10620 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10621 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010622 }
10623
10624 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010625 * Draw the shadow image for the upcoming drag. The shadow canvas was
10626 * created with the dimensions supplied by the
10627 * {@link #onProvideShadowMetrics(Point, Point)} callback.
Christopher Tate2c095f32010-10-04 14:13:40 -070010628 *
10629 * @param canvas
10630 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010631 public void onDrawShadow(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -070010632 final View view = mView.get();
10633 if (view != null) {
10634 view.draw(canvas);
10635 } else {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010636 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
Christopher Tatea0374192010-10-05 13:06:41 -070010637 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010638 }
10639 }
10640
10641 /**
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010642 * Drag and drop. App calls startDrag(), then callbacks to the shadow builder's
10643 * {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} and
10644 * {@link DragShadowBuilder#onDrawShadow(Canvas)} methods happen, then the drag
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010645 * operation is handed over to the OS.
Christopher Tatea53146c2010-09-07 11:57:52 -070010646 * !!! TODO: real docs
Christopher Tate407b4e92010-11-30 17:14:08 -080010647 *
10648 * @param data !!! TODO
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010649 * @param shadowBuilder !!! TODO
Christopher Tate407b4e92010-11-30 17:14:08 -080010650 * @param myLocalState An arbitrary object that will be passed as part of every DragEvent
10651 * delivered to the calling application during the course of the current drag operation.
10652 * This object is private to the application that called startDrag(), and is not
10653 * visible to other applications. It provides a lightweight way for the application to
10654 * propagate information from the initiator to the recipient of a drag within its own
10655 * application; for example, to help disambiguate between 'copy' and 'move' semantics.
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010656 * @param flags Flags affecting the drag operation. At present no flags are defined;
10657 * pass 0 for this parameter.
Christopher Tate407b4e92010-11-30 17:14:08 -080010658 * @return {@code true} if the drag operation was initiated successfully; {@code false} if
10659 * an error prevented the drag from taking place.
Christopher Tatea53146c2010-09-07 11:57:52 -070010660 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010661 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010662 Object myLocalState, int flags) {
Christopher Tate2c095f32010-10-04 14:13:40 -070010663 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010664 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
Christopher Tatea53146c2010-09-07 11:57:52 -070010665 }
10666 boolean okay = false;
10667
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010668 Point shadowSize = new Point();
10669 Point shadowTouchPoint = new Point();
10670 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
Christopher Tate2c095f32010-10-04 14:13:40 -070010671
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010672 if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
10673 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
10674 throw new IllegalStateException("Drag shadow dimensions must not be negative");
Christopher Tate2c095f32010-10-04 14:13:40 -070010675 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010676
Chris Tatea32dcf72010-10-14 12:13:50 -070010677 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010678 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
10679 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
Chris Tatea32dcf72010-10-14 12:13:50 -070010680 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010681 Surface surface = new Surface();
10682 try {
10683 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010684 flags, shadowSize.x, shadowSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -070010685 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -070010686 + " surface=" + surface);
10687 if (token != null) {
10688 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -070010689 try {
Chris Tate6b391282010-10-14 15:48:59 -070010690 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010691 shadowBuilder.onDrawShadow(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -070010692 } finally {
10693 surface.unlockCanvasAndPost(canvas);
10694 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010695
Christopher Tate407b4e92010-11-30 17:14:08 -080010696 final ViewRoot root = getViewRoot();
10697
10698 // Cache the local state object for delivery with DragEvents
10699 root.setLocalDragState(myLocalState);
10700
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010701 // repurpose 'shadowSize' for the last touch point
10702 root.getLastTouchPoint(shadowSize);
Christopher Tate2c095f32010-10-04 14:13:40 -070010703
Christopher Tatea53146c2010-09-07 11:57:52 -070010704 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010705 shadowSize.x, shadowSize.y,
10706 shadowTouchPoint.x, shadowTouchPoint.y, data);
Christopher Tate2c095f32010-10-04 14:13:40 -070010707 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070010708 }
10709 } catch (Exception e) {
10710 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
10711 surface.destroy();
10712 }
10713
10714 return okay;
10715 }
10716
Christopher Tatea53146c2010-09-07 11:57:52 -070010717 /**
10718 * Drag-and-drop event dispatch. The event.getAction() verb is one of the DragEvent
10719 * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
10720 *
10721 * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
10722 * being dragged. onDragEvent() should return 'true' if the view can handle
10723 * a drop of that content. A view that returns 'false' here will receive no
10724 * further calls to onDragEvent() about the drag/drop operation.
10725 *
10726 * For DRAG_ENTERED, event.getClipDescription() describes the content being
10727 * dragged. This will be the same content description passed in the
10728 * DRAG_STARTED_EVENT invocation.
10729 *
10730 * For DRAG_EXITED, event.getClipDescription() describes the content being
10731 * dragged. This will be the same content description passed in the
10732 * DRAG_STARTED_EVENT invocation. The view should return to its approriate
10733 * drag-acceptance visual state.
10734 *
10735 * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
10736 * coordinates of the current drag point. The view must return 'true' if it
10737 * can accept a drop of the current drag content, false otherwise.
10738 *
10739 * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
10740 * within the view; also, event.getClipData() returns the full data payload
10741 * being dropped. The view should return 'true' if it consumed the dropped
10742 * content, 'false' if it did not.
10743 *
10744 * For DRAG_ENDED_EVENT, the 'event' argument may be null. The view should return
10745 * to its normal visual state.
10746 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070010747 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070010748 return false;
10749 }
10750
10751 /**
10752 * Views typically don't need to override dispatchDragEvent(); it just calls
Chris Tate32affef2010-10-18 15:29:21 -070010753 * onDragEvent(event) and passes the result up appropriately.
Christopher Tatea53146c2010-09-07 11:57:52 -070010754 */
10755 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070010756 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10757 && mOnDragListener.onDrag(this, event)) {
10758 return true;
10759 }
Christopher Tatea53146c2010-09-07 11:57:52 -070010760 return onDragEvent(event);
10761 }
10762
10763 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070010764 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
10765 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070010766 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070010767 */
10768 public void onCloseSystemDialogs(String reason) {
10769 }
10770
10771 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010772 * Given a Drawable whose bounds have been set to draw into this view,
10773 * update a Region being computed for {@link #gatherTransparentRegion} so
10774 * that any non-transparent parts of the Drawable are removed from the
10775 * given transparent region.
10776 *
10777 * @param dr The Drawable whose transparency is to be applied to the region.
10778 * @param region A Region holding the current transparency information,
10779 * where any parts of the region that are set are considered to be
10780 * transparent. On return, this region will be modified to have the
10781 * transparency information reduced by the corresponding parts of the
10782 * Drawable that are not transparent.
10783 * {@hide}
10784 */
10785 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
10786 if (DBG) {
10787 Log.i("View", "Getting transparent region for: " + this);
10788 }
10789 final Region r = dr.getTransparentRegion();
10790 final Rect db = dr.getBounds();
10791 final AttachInfo attachInfo = mAttachInfo;
10792 if (r != null && attachInfo != null) {
10793 final int w = getRight()-getLeft();
10794 final int h = getBottom()-getTop();
10795 if (db.left > 0) {
10796 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
10797 r.op(0, 0, db.left, h, Region.Op.UNION);
10798 }
10799 if (db.right < w) {
10800 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
10801 r.op(db.right, 0, w, h, Region.Op.UNION);
10802 }
10803 if (db.top > 0) {
10804 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
10805 r.op(0, 0, w, db.top, Region.Op.UNION);
10806 }
10807 if (db.bottom < h) {
10808 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
10809 r.op(0, db.bottom, w, h, Region.Op.UNION);
10810 }
10811 final int[] location = attachInfo.mTransparentLocation;
10812 getLocationInWindow(location);
10813 r.translate(location[0], location[1]);
10814 region.op(r, Region.Op.INTERSECT);
10815 } else {
10816 region.op(db, Region.Op.DIFFERENCE);
10817 }
10818 }
10819
Adam Powelle14579b2009-12-16 18:39:52 -080010820 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010821 mHasPerformedLongPress = false;
10822
10823 if (mPendingCheckForLongPress == null) {
10824 mPendingCheckForLongPress = new CheckForLongPress();
10825 }
10826 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080010827 postDelayed(mPendingCheckForLongPress,
10828 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010829 }
10830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010831 /**
10832 * Inflate a view from an XML resource. This convenience method wraps the {@link
10833 * LayoutInflater} class, which provides a full range of options for view inflation.
10834 *
10835 * @param context The Context object for your activity or application.
10836 * @param resource The resource ID to inflate
10837 * @param root A view group that will be the parent. Used to properly inflate the
10838 * layout_* parameters.
10839 * @see LayoutInflater
10840 */
10841 public static View inflate(Context context, int resource, ViewGroup root) {
10842 LayoutInflater factory = LayoutInflater.from(context);
10843 return factory.inflate(resource, root);
10844 }
Romain Guy33e72ae2010-07-17 12:40:29 -070010845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010846 /**
Adam Powell637d3372010-08-25 14:37:03 -070010847 * Scroll the view with standard behavior for scrolling beyond the normal
10848 * content boundaries. Views that call this method should override
10849 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
10850 * results of an over-scroll operation.
10851 *
10852 * Views can use this method to handle any touch or fling-based scrolling.
10853 *
10854 * @param deltaX Change in X in pixels
10855 * @param deltaY Change in Y in pixels
10856 * @param scrollX Current X scroll value in pixels before applying deltaX
10857 * @param scrollY Current Y scroll value in pixels before applying deltaY
10858 * @param scrollRangeX Maximum content scroll range along the X axis
10859 * @param scrollRangeY Maximum content scroll range along the Y axis
10860 * @param maxOverScrollX Number of pixels to overscroll by in either direction
10861 * along the X axis.
10862 * @param maxOverScrollY Number of pixels to overscroll by in either direction
10863 * along the Y axis.
10864 * @param isTouchEvent true if this scroll operation is the result of a touch event.
10865 * @return true if scrolling was clamped to an over-scroll boundary along either
10866 * axis, false otherwise.
10867 */
10868 protected boolean overScrollBy(int deltaX, int deltaY,
10869 int scrollX, int scrollY,
10870 int scrollRangeX, int scrollRangeY,
10871 int maxOverScrollX, int maxOverScrollY,
10872 boolean isTouchEvent) {
10873 final int overScrollMode = mOverScrollMode;
10874 final boolean canScrollHorizontal =
10875 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
10876 final boolean canScrollVertical =
10877 computeVerticalScrollRange() > computeVerticalScrollExtent();
10878 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
10879 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
10880 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
10881 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
10882
10883 int newScrollX = scrollX + deltaX;
10884 if (!overScrollHorizontal) {
10885 maxOverScrollX = 0;
10886 }
10887
10888 int newScrollY = scrollY + deltaY;
10889 if (!overScrollVertical) {
10890 maxOverScrollY = 0;
10891 }
10892
10893 // Clamp values if at the limits and record
10894 final int left = -maxOverScrollX;
10895 final int right = maxOverScrollX + scrollRangeX;
10896 final int top = -maxOverScrollY;
10897 final int bottom = maxOverScrollY + scrollRangeY;
10898
10899 boolean clampedX = false;
10900 if (newScrollX > right) {
10901 newScrollX = right;
10902 clampedX = true;
10903 } else if (newScrollX < left) {
10904 newScrollX = left;
10905 clampedX = true;
10906 }
10907
10908 boolean clampedY = false;
10909 if (newScrollY > bottom) {
10910 newScrollY = bottom;
10911 clampedY = true;
10912 } else if (newScrollY < top) {
10913 newScrollY = top;
10914 clampedY = true;
10915 }
10916
10917 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
10918
10919 return clampedX || clampedY;
10920 }
10921
10922 /**
10923 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
10924 * respond to the results of an over-scroll operation.
10925 *
10926 * @param scrollX New X scroll value in pixels
10927 * @param scrollY New Y scroll value in pixels
10928 * @param clampedX True if scrollX was clamped to an over-scroll boundary
10929 * @param clampedY True if scrollY was clamped to an over-scroll boundary
10930 */
10931 protected void onOverScrolled(int scrollX, int scrollY,
10932 boolean clampedX, boolean clampedY) {
10933 // Intentionally empty.
10934 }
10935
10936 /**
10937 * Returns the over-scroll mode for this view. The result will be
10938 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10939 * (allow over-scrolling only if the view content is larger than the container),
10940 * or {@link #OVER_SCROLL_NEVER}.
10941 *
10942 * @return This view's over-scroll mode.
10943 */
10944 public int getOverScrollMode() {
10945 return mOverScrollMode;
10946 }
10947
10948 /**
10949 * Set the over-scroll mode for this view. Valid over-scroll modes are
10950 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
10951 * (allow over-scrolling only if the view content is larger than the container),
10952 * or {@link #OVER_SCROLL_NEVER}.
10953 *
10954 * Setting the over-scroll mode of a view will have an effect only if the
10955 * view is capable of scrolling.
10956 *
10957 * @param overScrollMode The new over-scroll mode for this view.
10958 */
10959 public void setOverScrollMode(int overScrollMode) {
10960 if (overScrollMode != OVER_SCROLL_ALWAYS &&
10961 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
10962 overScrollMode != OVER_SCROLL_NEVER) {
10963 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
10964 }
10965 mOverScrollMode = overScrollMode;
10966 }
10967
10968 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010969 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
10970 * Each MeasureSpec represents a requirement for either the width or the height.
10971 * A MeasureSpec is comprised of a size and a mode. There are three possible
10972 * modes:
10973 * <dl>
10974 * <dt>UNSPECIFIED</dt>
10975 * <dd>
10976 * The parent has not imposed any constraint on the child. It can be whatever size
10977 * it wants.
10978 * </dd>
10979 *
10980 * <dt>EXACTLY</dt>
10981 * <dd>
10982 * The parent has determined an exact size for the child. The child is going to be
10983 * given those bounds regardless of how big it wants to be.
10984 * </dd>
10985 *
10986 * <dt>AT_MOST</dt>
10987 * <dd>
10988 * The child can be as large as it wants up to the specified size.
10989 * </dd>
10990 * </dl>
10991 *
10992 * MeasureSpecs are implemented as ints to reduce object allocation. This class
10993 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
10994 */
10995 public static class MeasureSpec {
10996 private static final int MODE_SHIFT = 30;
10997 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
10998
10999 /**
11000 * Measure specification mode: The parent has not imposed any constraint
11001 * on the child. It can be whatever size it wants.
11002 */
11003 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
11004
11005 /**
11006 * Measure specification mode: The parent has determined an exact size
11007 * for the child. The child is going to be given those bounds regardless
11008 * of how big it wants to be.
11009 */
11010 public static final int EXACTLY = 1 << MODE_SHIFT;
11011
11012 /**
11013 * Measure specification mode: The child can be as large as it wants up
11014 * to the specified size.
11015 */
11016 public static final int AT_MOST = 2 << MODE_SHIFT;
11017
11018 /**
11019 * Creates a measure specification based on the supplied size and mode.
11020 *
11021 * The mode must always be one of the following:
11022 * <ul>
11023 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
11024 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
11025 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
11026 * </ul>
11027 *
11028 * @param size the size of the measure specification
11029 * @param mode the mode of the measure specification
11030 * @return the measure specification based on size and mode
11031 */
11032 public static int makeMeasureSpec(int size, int mode) {
11033 return size + mode;
11034 }
11035
11036 /**
11037 * Extracts the mode from the supplied measure specification.
11038 *
11039 * @param measureSpec the measure specification to extract the mode from
11040 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
11041 * {@link android.view.View.MeasureSpec#AT_MOST} or
11042 * {@link android.view.View.MeasureSpec#EXACTLY}
11043 */
11044 public static int getMode(int measureSpec) {
11045 return (measureSpec & MODE_MASK);
11046 }
11047
11048 /**
11049 * Extracts the size from the supplied measure specification.
11050 *
11051 * @param measureSpec the measure specification to extract the size from
11052 * @return the size in pixels defined in the supplied measure specification
11053 */
11054 public static int getSize(int measureSpec) {
11055 return (measureSpec & ~MODE_MASK);
11056 }
11057
11058 /**
11059 * Returns a String representation of the specified measure
11060 * specification.
11061 *
11062 * @param measureSpec the measure specification to convert to a String
11063 * @return a String with the following format: "MeasureSpec: MODE SIZE"
11064 */
11065 public static String toString(int measureSpec) {
11066 int mode = getMode(measureSpec);
11067 int size = getSize(measureSpec);
11068
11069 StringBuilder sb = new StringBuilder("MeasureSpec: ");
11070
11071 if (mode == UNSPECIFIED)
11072 sb.append("UNSPECIFIED ");
11073 else if (mode == EXACTLY)
11074 sb.append("EXACTLY ");
11075 else if (mode == AT_MOST)
11076 sb.append("AT_MOST ");
11077 else
11078 sb.append(mode).append(" ");
11079
11080 sb.append(size);
11081 return sb.toString();
11082 }
11083 }
11084
11085 class CheckForLongPress implements Runnable {
11086
11087 private int mOriginalWindowAttachCount;
11088
11089 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011090 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011091 && mOriginalWindowAttachCount == mWindowAttachCount) {
11092 if (performLongClick()) {
11093 mHasPerformedLongPress = true;
11094 }
11095 }
11096 }
11097
11098 public void rememberWindowAttachCount() {
11099 mOriginalWindowAttachCount = mWindowAttachCount;
11100 }
11101 }
Adam Powelle14579b2009-12-16 18:39:52 -080011102
11103 private final class CheckForTap implements Runnable {
11104 public void run() {
11105 mPrivateFlags &= ~PREPRESSED;
11106 mPrivateFlags |= PRESSED;
11107 refreshDrawableState();
11108 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
11109 postCheckForLongClick(ViewConfiguration.getTapTimeout());
11110 }
11111 }
11112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011113
Adam Powella35d7682010-03-12 14:48:13 -080011114 private final class PerformClick implements Runnable {
11115 public void run() {
11116 performClick();
11117 }
11118 }
11119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011120 /**
11121 * Interface definition for a callback to be invoked when a key event is
11122 * dispatched to this view. The callback will be invoked before the key
11123 * event is given to the view.
11124 */
11125 public interface OnKeyListener {
11126 /**
11127 * Called when a key is dispatched to a view. This allows listeners to
11128 * get a chance to respond before the target view.
11129 *
11130 * @param v The view the key has been dispatched to.
11131 * @param keyCode The code for the physical key that was pressed
11132 * @param event The KeyEvent object containing full information about
11133 * the event.
11134 * @return True if the listener has consumed the event, false otherwise.
11135 */
11136 boolean onKey(View v, int keyCode, KeyEvent event);
11137 }
11138
11139 /**
11140 * Interface definition for a callback to be invoked when a touch event is
11141 * dispatched to this view. The callback will be invoked before the touch
11142 * event is given to the view.
11143 */
11144 public interface OnTouchListener {
11145 /**
11146 * Called when a touch event is dispatched to a view. This allows listeners to
11147 * get a chance to respond before the target view.
11148 *
11149 * @param v The view the touch event has been dispatched to.
11150 * @param event The MotionEvent object containing full information about
11151 * the event.
11152 * @return True if the listener has consumed the event, false otherwise.
11153 */
11154 boolean onTouch(View v, MotionEvent event);
11155 }
11156
11157 /**
11158 * Interface definition for a callback to be invoked when a view has been clicked and held.
11159 */
11160 public interface OnLongClickListener {
11161 /**
11162 * Called when a view has been clicked and held.
11163 *
11164 * @param v The view that was clicked and held.
11165 *
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -080011166 * @return true if the callback consumed the long click, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011167 */
11168 boolean onLongClick(View v);
11169 }
11170
11171 /**
Chris Tate32affef2010-10-18 15:29:21 -070011172 * Interface definition for a callback to be invoked when a drag is being dispatched
11173 * to this view. The callback will be invoked before the hosting view's own
11174 * onDrag(event) method. If the listener wants to fall back to the hosting view's
11175 * onDrag(event) behavior, it should return 'false' from this callback.
11176 */
11177 public interface OnDragListener {
11178 /**
11179 * Called when a drag event is dispatched to a view. This allows listeners
11180 * to get a chance to override base View behavior.
11181 *
11182 * @param v The view the drag has been dispatched to.
11183 * @param event The DragEvent object containing full information
11184 * about the event.
11185 * @return true if the listener consumed the DragEvent, false in order to fall
11186 * back to the view's default handling.
11187 */
11188 boolean onDrag(View v, DragEvent event);
11189 }
11190
11191 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011192 * Interface definition for a callback to be invoked when the focus state of
11193 * a view changed.
11194 */
11195 public interface OnFocusChangeListener {
11196 /**
11197 * Called when the focus state of a view has changed.
11198 *
11199 * @param v The view whose state has changed.
11200 * @param hasFocus The new focus state of v.
11201 */
11202 void onFocusChange(View v, boolean hasFocus);
11203 }
11204
11205 /**
11206 * Interface definition for a callback to be invoked when a view is clicked.
11207 */
11208 public interface OnClickListener {
11209 /**
11210 * Called when a view has been clicked.
11211 *
11212 * @param v The view that was clicked.
11213 */
11214 void onClick(View v);
11215 }
11216
11217 /**
11218 * Interface definition for a callback to be invoked when the context menu
11219 * for this view is being built.
11220 */
11221 public interface OnCreateContextMenuListener {
11222 /**
11223 * Called when the context menu for this view is being built. It is not
11224 * safe to hold onto the menu after this method returns.
11225 *
11226 * @param menu The context menu that is being built
11227 * @param v The view for which the context menu is being built
11228 * @param menuInfo Extra information about the item for which the
11229 * context menu should be shown. This information will vary
11230 * depending on the class of v.
11231 */
11232 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
11233 }
11234
11235 private final class UnsetPressedState implements Runnable {
11236 public void run() {
11237 setPressed(false);
11238 }
11239 }
11240
11241 /**
11242 * Base class for derived classes that want to save and restore their own
11243 * state in {@link android.view.View#onSaveInstanceState()}.
11244 */
11245 public static class BaseSavedState extends AbsSavedState {
11246 /**
11247 * Constructor used when reading from a parcel. Reads the state of the superclass.
11248 *
11249 * @param source
11250 */
11251 public BaseSavedState(Parcel source) {
11252 super(source);
11253 }
11254
11255 /**
11256 * Constructor called by derived classes when creating their SavedState objects
11257 *
11258 * @param superState The state of the superclass of this view
11259 */
11260 public BaseSavedState(Parcelable superState) {
11261 super(superState);
11262 }
11263
11264 public static final Parcelable.Creator<BaseSavedState> CREATOR =
11265 new Parcelable.Creator<BaseSavedState>() {
11266 public BaseSavedState createFromParcel(Parcel in) {
11267 return new BaseSavedState(in);
11268 }
11269
11270 public BaseSavedState[] newArray(int size) {
11271 return new BaseSavedState[size];
11272 }
11273 };
11274 }
11275
11276 /**
11277 * A set of information given to a view when it is attached to its parent
11278 * window.
11279 */
11280 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011281 interface Callbacks {
11282 void playSoundEffect(int effectId);
11283 boolean performHapticFeedback(int effectId, boolean always);
11284 }
11285
11286 /**
11287 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
11288 * to a Handler. This class contains the target (View) to invalidate and
11289 * the coordinates of the dirty rectangle.
11290 *
11291 * For performance purposes, this class also implements a pool of up to
11292 * POOL_LIMIT objects that get reused. This reduces memory allocations
11293 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011294 */
Romain Guyd928d682009-03-31 17:52:16 -070011295 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011296 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070011297 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
11298 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070011299 public InvalidateInfo newInstance() {
11300 return new InvalidateInfo();
11301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011302
Romain Guyd928d682009-03-31 17:52:16 -070011303 public void onAcquired(InvalidateInfo element) {
11304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011305
Romain Guyd928d682009-03-31 17:52:16 -070011306 public void onReleased(InvalidateInfo element) {
11307 }
11308 }, POOL_LIMIT)
11309 );
11310
11311 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011312
11313 View target;
11314
11315 int left;
11316 int top;
11317 int right;
11318 int bottom;
11319
Romain Guyd928d682009-03-31 17:52:16 -070011320 public void setNextPoolable(InvalidateInfo element) {
11321 mNext = element;
11322 }
11323
11324 public InvalidateInfo getNextPoolable() {
11325 return mNext;
11326 }
11327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011328 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070011329 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011330 }
11331
11332 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070011333 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011334 }
11335 }
11336
11337 final IWindowSession mSession;
11338
11339 final IWindow mWindow;
11340
11341 final IBinder mWindowToken;
11342
11343 final Callbacks mRootCallbacks;
11344
11345 /**
11346 * The top view of the hierarchy.
11347 */
11348 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070011349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011350 IBinder mPanelParentWindowToken;
11351 Surface mSurface;
11352
Romain Guyb051e892010-09-28 19:09:36 -070011353 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080011354 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070011355 HardwareRenderer mHardwareRenderer;
Romain Guy2bffd262010-09-12 17:40:02 -070011356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011357 /**
Romain Guy8506ab42009-06-11 17:35:47 -070011358 * Scale factor used by the compatibility mode
11359 */
11360 float mApplicationScale;
11361
11362 /**
11363 * Indicates whether the application is in compatibility mode
11364 */
11365 boolean mScalingRequired;
11366
11367 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011368 * Left position of this view's window
11369 */
11370 int mWindowLeft;
11371
11372 /**
11373 * Top position of this view's window
11374 */
11375 int mWindowTop;
11376
11377 /**
Adam Powell26153a32010-11-08 15:22:27 -080011378 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070011379 */
Adam Powell26153a32010-11-08 15:22:27 -080011380 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070011381
11382 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011383 * For windows that are full-screen but using insets to layout inside
11384 * of the screen decorations, these are the current insets for the
11385 * content of the window.
11386 */
11387 final Rect mContentInsets = new Rect();
11388
11389 /**
11390 * For windows that are full-screen but using insets to layout inside
11391 * of the screen decorations, these are the current insets for the
11392 * actual visible parts of the window.
11393 */
11394 final Rect mVisibleInsets = new Rect();
11395
11396 /**
11397 * The internal insets given by this window. This value is
11398 * supplied by the client (through
11399 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
11400 * be given to the window manager when changed to be used in laying
11401 * out windows behind it.
11402 */
11403 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
11404 = new ViewTreeObserver.InternalInsetsInfo();
11405
11406 /**
11407 * All views in the window's hierarchy that serve as scroll containers,
11408 * used to determine if the window can be resized or must be panned
11409 * to adjust for a soft input area.
11410 */
11411 final ArrayList<View> mScrollContainers = new ArrayList<View>();
11412
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070011413 final KeyEvent.DispatcherState mKeyDispatchState
11414 = new KeyEvent.DispatcherState();
11415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011416 /**
11417 * Indicates whether the view's window currently has the focus.
11418 */
11419 boolean mHasWindowFocus;
11420
11421 /**
11422 * The current visibility of the window.
11423 */
11424 int mWindowVisibility;
11425
11426 /**
11427 * Indicates the time at which drawing started to occur.
11428 */
11429 long mDrawingTime;
11430
11431 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070011432 * Indicates whether or not ignoring the DIRTY_MASK flags.
11433 */
11434 boolean mIgnoreDirtyState;
11435
11436 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011437 * Indicates whether the view's window is currently in touch mode.
11438 */
11439 boolean mInTouchMode;
11440
11441 /**
11442 * Indicates that ViewRoot should trigger a global layout change
11443 * the next time it performs a traversal
11444 */
11445 boolean mRecomputeGlobalAttributes;
11446
11447 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011448 * Set during a traveral if any views want to keep the screen on.
11449 */
11450 boolean mKeepScreenOn;
11451
11452 /**
11453 * Set if the visibility of any views has changed.
11454 */
11455 boolean mViewVisibilityChanged;
11456
11457 /**
11458 * Set to true if a view has been scrolled.
11459 */
11460 boolean mViewScrollChanged;
11461
11462 /**
11463 * Global to the view hierarchy used as a temporary for dealing with
11464 * x/y points in the transparent region computations.
11465 */
11466 final int[] mTransparentLocation = new int[2];
11467
11468 /**
11469 * Global to the view hierarchy used as a temporary for dealing with
11470 * x/y points in the ViewGroup.invalidateChild implementation.
11471 */
11472 final int[] mInvalidateChildLocation = new int[2];
11473
Chet Haasec3aa3612010-06-17 08:50:37 -070011474
11475 /**
11476 * Global to the view hierarchy used as a temporary for dealing with
11477 * x/y location when view is transformed.
11478 */
11479 final float[] mTmpTransformLocation = new float[2];
11480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011481 /**
11482 * The view tree observer used to dispatch global events like
11483 * layout, pre-draw, touch mode change, etc.
11484 */
11485 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11486
11487 /**
11488 * A Canvas used by the view hierarchy to perform bitmap caching.
11489 */
11490 Canvas mCanvas;
11491
11492 /**
11493 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11494 * handler can be used to pump events in the UI events queue.
11495 */
11496 final Handler mHandler;
11497
11498 /**
11499 * Identifier for messages requesting the view to be invalidated.
11500 * Such messages should be sent to {@link #mHandler}.
11501 */
11502 static final int INVALIDATE_MSG = 0x1;
11503
11504 /**
11505 * Identifier for messages requesting the view to invalidate a region.
11506 * Such messages should be sent to {@link #mHandler}.
11507 */
11508 static final int INVALIDATE_RECT_MSG = 0x2;
11509
11510 /**
11511 * Temporary for use in computing invalidate rectangles while
11512 * calling up the hierarchy.
11513 */
11514 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070011515
11516 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070011517 * Temporary for use in computing hit areas with transformed views
11518 */
11519 final RectF mTmpTransformRect = new RectF();
11520
11521 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070011522 * Temporary list for use in collecting focusable descendents of a view.
11523 */
11524 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
11525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011526 /**
11527 * Creates a new set of attachment information with the specified
11528 * events handler and thread.
11529 *
11530 * @param handler the events handler the view must use
11531 */
11532 AttachInfo(IWindowSession session, IWindow window,
11533 Handler handler, Callbacks effectPlayer) {
11534 mSession = session;
11535 mWindow = window;
11536 mWindowToken = window.asBinder();
11537 mHandler = handler;
11538 mRootCallbacks = effectPlayer;
11539 }
11540 }
11541
11542 /**
11543 * <p>ScrollabilityCache holds various fields used by a View when scrolling
11544 * is supported. This avoids keeping too many unused fields in most
11545 * instances of View.</p>
11546 */
Mike Cleronf116bf82009-09-27 19:14:12 -070011547 private static class ScrollabilityCache implements Runnable {
11548
11549 /**
11550 * Scrollbars are not visible
11551 */
11552 public static final int OFF = 0;
11553
11554 /**
11555 * Scrollbars are visible
11556 */
11557 public static final int ON = 1;
11558
11559 /**
11560 * Scrollbars are fading away
11561 */
11562 public static final int FADING = 2;
11563
11564 public boolean fadeScrollBars;
11565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011566 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070011567 public int scrollBarDefaultDelayBeforeFade;
11568 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011569
11570 public int scrollBarSize;
11571 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070011572 public float[] interpolatorValues;
11573 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011574
11575 public final Paint paint;
11576 public final Matrix matrix;
11577 public Shader shader;
11578
Mike Cleronf116bf82009-09-27 19:14:12 -070011579 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
11580
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011581 private static final float[] OPAQUE = { 255 };
11582 private static final float[] TRANSPARENT = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070011583
11584 /**
11585 * When fading should start. This time moves into the future every time
11586 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11587 */
11588 public long fadeStartTime;
11589
11590
11591 /**
11592 * The current state of the scrollbars: ON, OFF, or FADING
11593 */
11594 public int state = OFF;
11595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011596 private int mLastColor;
11597
Mike Cleronf116bf82009-09-27 19:14:12 -070011598 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011599 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11600 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070011601 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11602 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011603
11604 paint = new Paint();
11605 matrix = new Matrix();
11606 // use use a height of 1, and then wack the matrix each time we
11607 // actually use it.
11608 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011610 paint.setShader(shader);
11611 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070011612 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011613 }
Romain Guy8506ab42009-06-11 17:35:47 -070011614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011615 public void setFadeColor(int color) {
11616 if (color != 0 && color != mLastColor) {
11617 mLastColor = color;
11618 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070011619
Romain Guye55e1a72009-08-27 10:42:26 -070011620 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
11621 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011623 paint.setShader(shader);
11624 // Restore the default transfer mode (src_over)
11625 paint.setXfermode(null);
11626 }
11627 }
Mike Cleronf116bf82009-09-27 19:14:12 -070011628
11629 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070011630 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070011631 if (now >= fadeStartTime) {
11632
11633 // the animation fades the scrollbars out by changing
11634 // the opacity (alpha) from fully opaque to fully
11635 // transparent
11636 int nextFrame = (int) now;
11637 int framesCount = 0;
11638
11639 Interpolator interpolator = scrollBarInterpolator;
11640
11641 // Start opaque
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011642 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
Mike Cleronf116bf82009-09-27 19:14:12 -070011643
11644 // End transparent
11645 nextFrame += scrollBarFadeDuration;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011646 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
Mike Cleronf116bf82009-09-27 19:14:12 -070011647
11648 state = FADING;
11649
11650 // Kick off the fade animation
11651 host.invalidate();
11652 }
11653 }
11654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011655 }
11656}