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