blob: 47dae037e26b404aea64480d91598fafb86758c6 [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
svetoslavganov75986cf2009-05-14 22:28:01 -070019import com.android.internal.R;
20import com.android.internal.view.menu.MenuBuilder;
21
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080023import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.res.Resources;
25import android.content.res.TypedArray;
26import android.graphics.Bitmap;
Adam Powell2b342f02010-08-18 18:14:13 -070027import android.graphics.Camera;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import 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;
svetoslavganov75986cf2009-05-14 22:28:01 -070061import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070065import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070066import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.view.inputmethod.InputConnection;
68import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.widget.ScrollBarDrawable;
70
svetoslavganov75986cf2009-05-14 22:28:01 -070071import java.lang.reflect.InvocationTargetException;
72import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.util.ArrayList;
74import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070075import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070076import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077
78/**
79 * <p>
80 * This class represents the basic building block for user interface components. A View
81 * occupies a rectangular area on the screen and is responsible for drawing and
82 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070083 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
85 * are invisible containers that hold other Views (or other ViewGroups) and define
86 * their layout properties.
87 * </p>
88 *
89 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070090 * <p>For an introduction to using this class to develop your
91 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070093 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
95 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
102 * </p>
103 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700104 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 * <a name="Using"></a>
106 * <h3>Using Views</h3>
107 * <p>
108 * All of the views in a window are arranged in a single tree. You can add views
109 * either from code or by specifying a tree of views in one or more XML layout
110 * files. There are many specialized subclasses of views that act as controls or
111 * are capable of displaying text, images, or other content.
112 * </p>
113 * <p>
114 * Once you have created a tree of views, there are typically a few types of
115 * common operations you may wish to perform:
116 * <ul>
117 * <li><strong>Set properties:</strong> for example setting the text of a
118 * {@link android.widget.TextView}. The available properties and the methods
119 * that set them will vary among the different subclasses of views. Note that
120 * properties that are known at build time can be set in the XML layout
121 * files.</li>
122 * <li><strong>Set focus:</strong> The framework will handled moving focus in
123 * response to user input. To force focus to a specific view, call
124 * {@link #requestFocus}.</li>
125 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
126 * that will be notified when something interesting happens to the view. For
127 * example, all views will let you set a listener to be notified when the view
128 * gains or loses focus. You can register such a listener using
129 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
130 * specialized listeners. For example, a Button exposes a listener to notify
131 * clients when the button is clicked.</li>
132 * <li><strong>Set visibility:</strong> You can hide or show views using
133 * {@link #setVisibility}.</li>
134 * </ul>
135 * </p>
136 * <p><em>
137 * Note: The Android framework is responsible for measuring, laying out and
138 * drawing views. You should not call methods that perform these actions on
139 * views yourself unless you are actually implementing a
140 * {@link android.view.ViewGroup}.
141 * </em></p>
142 *
143 * <a name="Lifecycle"></a>
144 * <h3>Implementing a Custom View</h3>
145 *
146 * <p>
147 * To implement a custom view, you will usually begin by providing overrides for
148 * some of the standard methods that the framework calls on all views. You do
149 * not need to override all of these methods. In fact, you can start by just
150 * overriding {@link #onDraw(android.graphics.Canvas)}.
151 * <table border="2" width="85%" align="center" cellpadding="5">
152 * <thead>
153 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
154 * </thead>
155 *
156 * <tbody>
157 * <tr>
158 * <td rowspan="2">Creation</td>
159 * <td>Constructors</td>
160 * <td>There is a form of the constructor that are called when the view
161 * is created from code and a form that is called when the view is
162 * inflated from a layout file. The second form should parse and apply
163 * any attributes defined in the layout file.
164 * </td>
165 * </tr>
166 * <tr>
167 * <td><code>{@link #onFinishInflate()}</code></td>
168 * <td>Called after a view and all of its children has been inflated
169 * from XML.</td>
170 * </tr>
171 *
172 * <tr>
173 * <td rowspan="3">Layout</td>
174 * <td><code>{@link #onMeasure}</code></td>
175 * <td>Called to determine the size requirements for this view and all
176 * of its children.
177 * </td>
178 * </tr>
179 * <tr>
180 * <td><code>{@link #onLayout}</code></td>
181 * <td>Called when this view should assign a size and position to all
182 * of its children.
183 * </td>
184 * </tr>
185 * <tr>
186 * <td><code>{@link #onSizeChanged}</code></td>
187 * <td>Called when the size of this view has changed.
188 * </td>
189 * </tr>
190 *
191 * <tr>
192 * <td>Drawing</td>
193 * <td><code>{@link #onDraw}</code></td>
194 * <td>Called when the view should render its content.
195 * </td>
196 * </tr>
197 *
198 * <tr>
199 * <td rowspan="4">Event processing</td>
200 * <td><code>{@link #onKeyDown}</code></td>
201 * <td>Called when a new key event occurs.
202 * </td>
203 * </tr>
204 * <tr>
205 * <td><code>{@link #onKeyUp}</code></td>
206 * <td>Called when a key up event occurs.
207 * </td>
208 * </tr>
209 * <tr>
210 * <td><code>{@link #onTrackballEvent}</code></td>
211 * <td>Called when a trackball motion event occurs.
212 * </td>
213 * </tr>
214 * <tr>
215 * <td><code>{@link #onTouchEvent}</code></td>
216 * <td>Called when a touch screen motion event occurs.
217 * </td>
218 * </tr>
219 *
220 * <tr>
221 * <td rowspan="2">Focus</td>
222 * <td><code>{@link #onFocusChanged}</code></td>
223 * <td>Called when the view gains or loses focus.
224 * </td>
225 * </tr>
226 *
227 * <tr>
228 * <td><code>{@link #onWindowFocusChanged}</code></td>
229 * <td>Called when the window containing the view gains or loses focus.
230 * </td>
231 * </tr>
232 *
233 * <tr>
234 * <td rowspan="3">Attaching</td>
235 * <td><code>{@link #onAttachedToWindow()}</code></td>
236 * <td>Called when the view is attached to a window.
237 * </td>
238 * </tr>
239 *
240 * <tr>
241 * <td><code>{@link #onDetachedFromWindow}</code></td>
242 * <td>Called when the view is detached from its window.
243 * </td>
244 * </tr>
245 *
246 * <tr>
247 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
248 * <td>Called when the visibility of the window containing the view
249 * has changed.
250 * </td>
251 * </tr>
252 * </tbody>
253 *
254 * </table>
255 * </p>
256 *
257 * <a name="IDs"></a>
258 * <h3>IDs</h3>
259 * Views may have an integer id associated with them. These ids are typically
260 * assigned in the layout XML files, and are used to find specific views within
261 * the view tree. A common pattern is to:
262 * <ul>
263 * <li>Define a Button in the layout file and assign it a unique ID.
264 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700265 * &lt;Button
266 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 * android:layout_width="wrap_content"
268 * android:layout_height="wrap_content"
269 * android:text="@string/my_button_text"/&gt;
270 * </pre></li>
271 * <li>From the onCreate method of an Activity, find the Button
272 * <pre class="prettyprint">
273 * Button myButton = (Button) findViewById(R.id.my_button);
274 * </pre></li>
275 * </ul>
276 * <p>
277 * View IDs need not be unique throughout the tree, but it is good practice to
278 * ensure that they are at least unique within the part of the tree you are
279 * searching.
280 * </p>
281 *
282 * <a name="Position"></a>
283 * <h3>Position</h3>
284 * <p>
285 * The geometry of a view is that of a rectangle. A view has a location,
286 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
287 * two dimensions, expressed as a width and a height. The unit for location
288 * and dimensions is the pixel.
289 * </p>
290 *
291 * <p>
292 * It is possible to retrieve the location of a view by invoking the methods
293 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
294 * coordinate of the rectangle representing the view. The latter returns the
295 * top, or Y, coordinate of the rectangle representing the view. These methods
296 * both return the location of the view relative to its parent. For instance,
297 * when getLeft() returns 20, that means the view is located 20 pixels to the
298 * right of the left edge of its direct parent.
299 * </p>
300 *
301 * <p>
302 * In addition, several convenience methods are offered to avoid unnecessary
303 * computations, namely {@link #getRight()} and {@link #getBottom()}.
304 * These methods return the coordinates of the right and bottom edges of the
305 * rectangle representing the view. For instance, calling {@link #getRight()}
306 * is similar to the following computation: <code>getLeft() + getWidth()</code>
307 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
308 * </p>
309 *
310 * <a name="SizePaddingMargins"></a>
311 * <h3>Size, padding and margins</h3>
312 * <p>
313 * The size of a view is expressed with a width and a height. A view actually
314 * possess two pairs of width and height values.
315 * </p>
316 *
317 * <p>
318 * The first pair is known as <em>measured width</em> and
319 * <em>measured height</em>. These dimensions define how big a view wants to be
320 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
321 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
322 * and {@link #getMeasuredHeight()}.
323 * </p>
324 *
325 * <p>
326 * The second pair is simply known as <em>width</em> and <em>height</em>, or
327 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
328 * dimensions define the actual size of the view on screen, at drawing time and
329 * after layout. These values may, but do not have to, be different from the
330 * measured width and height. The width and height can be obtained by calling
331 * {@link #getWidth()} and {@link #getHeight()}.
332 * </p>
333 *
334 * <p>
335 * To measure its dimensions, a view takes into account its padding. The padding
336 * is expressed in pixels for the left, top, right and bottom parts of the view.
337 * Padding can be used to offset the content of the view by a specific amount of
338 * pixels. For instance, a left padding of 2 will push the view's content by
339 * 2 pixels to the right of the left edge. Padding can be set using the
340 * {@link #setPadding(int, int, int, int)} method and queried by calling
341 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
342 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
343 * </p>
344 *
345 * <p>
346 * Even though a view can define a padding, it does not provide any support for
347 * margins. However, view groups provide such a support. Refer to
348 * {@link android.view.ViewGroup} and
349 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
350 * </p>
351 *
352 * <a name="Layout"></a>
353 * <h3>Layout</h3>
354 * <p>
355 * Layout is a two pass process: a measure pass and a layout pass. The measuring
356 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
357 * of the view tree. Each view pushes dimension specifications down the tree
358 * during the recursion. At the end of the measure pass, every view has stored
359 * its measurements. The second pass happens in
360 * {@link #layout(int,int,int,int)} and is also top-down. During
361 * this pass each parent is responsible for positioning all of its children
362 * using the sizes computed in the measure pass.
363 * </p>
364 *
365 * <p>
366 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
367 * {@link #getMeasuredHeight()} values must be set, along with those for all of
368 * that view's descendants. A view's measured width and measured height values
369 * must respect the constraints imposed by the view's parents. This guarantees
370 * that at the end of the measure pass, all parents accept all of their
371 * children's measurements. A parent view may call measure() more than once on
372 * its children. For example, the parent may measure each child once with
373 * unspecified dimensions to find out how big they want to be, then call
374 * measure() on them again with actual numbers if the sum of all the children's
375 * unconstrained sizes is too big or too small.
376 * </p>
377 *
378 * <p>
379 * The measure pass uses two classes to communicate dimensions. The
380 * {@link MeasureSpec} class is used by views to tell their parents how they
381 * want to be measured and positioned. The base LayoutParams class just
382 * describes how big the view wants to be for both width and height. For each
383 * dimension, it can specify one of:
384 * <ul>
385 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800386 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 * (minus padding)
388 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
389 * enclose its content (plus padding).
390 * </ul>
391 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
392 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
393 * an X and Y value.
394 * </p>
395 *
396 * <p>
397 * MeasureSpecs are used to push requirements down the tree from parent to
398 * child. A MeasureSpec can be in one of three modes:
399 * <ul>
400 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
401 * of a child view. For example, a LinearLayout may call measure() on its child
402 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
403 * tall the child view wants to be given a width of 240 pixels.
404 * <li>EXACTLY: This is used by the parent to impose an exact size on the
405 * child. The child must use this size, and guarantee that all of its
406 * descendants will fit within this size.
407 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
408 * child. The child must gurantee that it and all of its descendants will fit
409 * within this size.
410 * </ul>
411 * </p>
412 *
413 * <p>
414 * To intiate a layout, call {@link #requestLayout}. This method is typically
415 * called by a view on itself when it believes that is can no longer fit within
416 * its current bounds.
417 * </p>
418 *
419 * <a name="Drawing"></a>
420 * <h3>Drawing</h3>
421 * <p>
422 * Drawing is handled by walking the tree and rendering each view that
423 * intersects the the invalid region. Because the tree is traversed in-order,
424 * this means that parents will draw before (i.e., behind) their children, with
425 * siblings drawn in the order they appear in the tree.
426 * If you set a background drawable for a View, then the View will draw it for you
427 * before calling back to its <code>onDraw()</code> method.
428 * </p>
429 *
430 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700431 * Note that the framework will not draw views that are not in the invalid region.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 * </p>
433 *
434 * <p>
435 * To force a view to draw, call {@link #invalidate()}.
436 * </p>
437 *
438 * <a name="EventHandlingThreading"></a>
439 * <h3>Event Handling and Threading</h3>
440 * <p>
441 * The basic cycle of a view is as follows:
442 * <ol>
443 * <li>An event comes in and is dispatched to the appropriate view. The view
444 * handles the event and notifies any listeners.</li>
445 * <li>If in the course of processing the event, the view's bounds may need
446 * to be changed, the view will call {@link #requestLayout()}.</li>
447 * <li>Similarly, if in the course of processing the event the view's appearance
448 * may need to be changed, the view will call {@link #invalidate()}.</li>
449 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
450 * the framework will take care of measuring, laying out, and drawing the tree
451 * as appropriate.</li>
452 * </ol>
453 * </p>
454 *
455 * <p><em>Note: The entire view tree is single threaded. You must always be on
456 * the UI thread when calling any method on any view.</em>
457 * If you are doing work on other threads and want to update the state of a view
458 * from that thread, you should use a {@link Handler}.
459 * </p>
460 *
461 * <a name="FocusHandling"></a>
462 * <h3>Focus Handling</h3>
463 * <p>
464 * The framework will handle routine focus movement in response to user input.
465 * This includes changing the focus as views are removed or hidden, or as new
466 * views become available. Views indicate their willingness to take focus
467 * through the {@link #isFocusable} method. To change whether a view can take
468 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
469 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
470 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
471 * </p>
472 * <p>
473 * Focus movement is based on an algorithm which finds the nearest neighbor in a
474 * given direction. In rare cases, the default algorithm may not match the
475 * intended behavior of the developer. In these situations, you can provide
476 * explicit overrides by using these XML attributes in the layout file:
477 * <pre>
478 * nextFocusDown
479 * nextFocusLeft
480 * nextFocusRight
481 * nextFocusUp
482 * </pre>
483 * </p>
484 *
485 *
486 * <p>
487 * To get a particular view to take focus, call {@link #requestFocus()}.
488 * </p>
489 *
490 * <a name="TouchMode"></a>
491 * <h3>Touch Mode</h3>
492 * <p>
493 * When a user is navigating a user interface via directional keys such as a D-pad, it is
494 * necessary to give focus to actionable items such as buttons so the user can see
495 * what will take input. If the device has touch capabilities, however, and the user
496 * begins interacting with the interface by touching it, it is no longer necessary to
497 * always highlight, or give focus to, a particular view. This motivates a mode
498 * for interaction named 'touch mode'.
499 * </p>
500 * <p>
501 * For a touch capable device, once the user touches the screen, the device
502 * will enter touch mode. From this point onward, only views for which
503 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
504 * Other views that are touchable, like buttons, will not take focus when touched; they will
505 * only fire the on click listeners.
506 * </p>
507 * <p>
508 * Any time a user hits a directional key, such as a D-pad direction, the view device will
509 * exit touch mode, and find a view to take focus, so that the user may resume interacting
510 * with the user interface without touching the screen again.
511 * </p>
512 * <p>
513 * The touch mode state is maintained across {@link android.app.Activity}s. Call
514 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
515 * </p>
516 *
517 * <a name="Scrolling"></a>
518 * <h3>Scrolling</h3>
519 * <p>
520 * The framework provides basic support for views that wish to internally
521 * scroll their content. This includes keeping track of the X and Y scroll
522 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700523 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
524 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 * </p>
526 *
527 * <a name="Tags"></a>
528 * <h3>Tags</h3>
529 * <p>
530 * Unlike IDs, tags are not used to identify views. Tags are essentially an
531 * extra piece of information that can be associated with a view. They are most
532 * often used as a convenience to store data related to views in the views
533 * themselves rather than by putting them in a separate structure.
534 * </p>
535 *
536 * <a name="Animation"></a>
537 * <h3>Animation</h3>
538 * <p>
539 * You can attach an {@link Animation} object to a view using
540 * {@link #setAnimation(Animation)} or
541 * {@link #startAnimation(Animation)}. The animation can alter the scale,
542 * rotation, translation and alpha of a view over time. If the animation is
543 * attached to a view that has children, the animation will affect the entire
544 * subtree rooted by that node. When an animation is started, the framework will
545 * take care of redrawing the appropriate views until the animation completes.
546 * </p>
547 *
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 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001378 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 protected int mMeasuredWidth;
1380
1381 /**
1382 * Height as measured during measure pass.
1383 * {@hide}
1384 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001385 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 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 */
Romain Guy2542d192010-08-18 11:47:12 -07001660 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001661
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 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001732 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 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 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001739 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 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 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001746 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 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 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001753 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 protected int mBottom;
1755
1756 /**
1757 * The offset, in pixels, by which the content of this view is scrolled
1758 * horizontally.
1759 * {@hide}
1760 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001761 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 protected int mScrollX;
1763 /**
1764 * The offset, in pixels, by which the content of this view is scrolled
1765 * vertically.
1766 * {@hide}
1767 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001768 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 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 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001776 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 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 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001783 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 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 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001790 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 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 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001797 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 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 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001808 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 int mUserPaddingRight;
1810
1811 /**
1812 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1813 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001814 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 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 /**
Chet Haase21cd1382010-09-01 17:42:29 -07001841 * Listeners for layout change events.
1842 */
1843 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
1844
1845 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 * Listener used to dispatch click events.
1847 * This field should be made private, so it is hidden from the SDK.
1848 * {@hide}
1849 */
1850 protected OnClickListener mOnClickListener;
1851
1852 /**
1853 * Listener used to dispatch long click events.
1854 * This field should be made private, so it is hidden from the SDK.
1855 * {@hide}
1856 */
1857 protected OnLongClickListener mOnLongClickListener;
1858
1859 /**
1860 * Listener used to build the context menu.
1861 * This field should be made private, so it is hidden from the SDK.
1862 * {@hide}
1863 */
1864 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
1865
1866 private OnKeyListener mOnKeyListener;
1867
1868 private OnTouchListener mOnTouchListener;
1869
1870 /**
1871 * The application environment this view lives in.
1872 * This field should be made private, so it is hidden from the SDK.
1873 * {@hide}
1874 */
1875 protected Context mContext;
1876
1877 private ScrollabilityCache mScrollCache;
1878
1879 private int[] mDrawableState = null;
1880
Romain Guy02890fd2010-08-06 17:58:44 -07001881 private Bitmap mDrawingCache;
1882 private Bitmap mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883
1884 /**
1885 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
1886 * the user may specify which view to go to next.
1887 */
1888 private int mNextFocusLeftId = View.NO_ID;
1889
1890 /**
1891 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
1892 * the user may specify which view to go to next.
1893 */
1894 private int mNextFocusRightId = View.NO_ID;
1895
1896 /**
1897 * When this view has focus and the next focus is {@link #FOCUS_UP},
1898 * the user may specify which view to go to next.
1899 */
1900 private int mNextFocusUpId = View.NO_ID;
1901
1902 /**
1903 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
1904 * the user may specify which view to go to next.
1905 */
1906 private int mNextFocusDownId = View.NO_ID;
1907
1908 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08001909 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08001910 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08001911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 private UnsetPressedState mUnsetPressedState;
1913
1914 /**
1915 * Whether the long press's action has been invoked. The tap's action is invoked on the
1916 * up event while a long press is invoked as soon as the long press duration is reached, so
1917 * a long press could be performed before the tap is checked, in which case the tap's action
1918 * should not be invoked.
1919 */
1920 private boolean mHasPerformedLongPress;
1921
1922 /**
1923 * The minimum height of the view. We'll try our best to have the height
1924 * of this view to at least this amount.
1925 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001926 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 private int mMinHeight;
1928
1929 /**
1930 * The minimum width of the view. We'll try our best to have the width
1931 * of this view to at least this amount.
1932 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001933 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 private int mMinWidth;
1935
1936 /**
1937 * The delegate to handle touch events that are physically in this view
1938 * but should be handled by another view.
1939 */
1940 private TouchDelegate mTouchDelegate = null;
1941
1942 /**
1943 * Solid color to use as a background when creating the drawing cache. Enables
1944 * the cache to use 16 bit bitmaps instead of 32 bit.
1945 */
1946 private int mDrawingCacheBackgroundColor = 0;
1947
1948 /**
1949 * Special tree observer used when mAttachInfo is null.
1950 */
1951 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08001952
1953 /**
1954 * Cache the touch slop from the context that created the view.
1955 */
1956 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957
1958 // Used for debug only
1959 static long sInstanceCount = 0;
1960
1961 /**
1962 * Simple constructor to use when creating a view from code.
1963 *
1964 * @param context The Context the view is running in, through which it can
1965 * access the current theme, resources, etc.
1966 */
1967 public View(Context context) {
1968 mContext = context;
1969 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07001970 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Carl Shapiro82fe5642010-02-24 00:14:23 -08001971 // Used for debug only
1972 //++sInstanceCount;
Adam Powelle14579b2009-12-16 18:39:52 -08001973 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 }
1975
1976 /**
1977 * Constructor that is called when inflating a view from XML. This is called
1978 * when a view is being constructed from an XML file, supplying attributes
1979 * that were specified in the XML file. This version uses a default style of
1980 * 0, so the only attribute values applied are those in the Context's Theme
1981 * and the given AttributeSet.
1982 *
1983 * <p>
1984 * The method onFinishInflate() will be called after all children have been
1985 * added.
1986 *
1987 * @param context The Context the view is running in, through which it can
1988 * access the current theme, resources, etc.
1989 * @param attrs The attributes of the XML tag that is inflating the view.
1990 * @see #View(Context, AttributeSet, int)
1991 */
1992 public View(Context context, AttributeSet attrs) {
1993 this(context, attrs, 0);
1994 }
1995
1996 /**
1997 * Perform inflation from XML and apply a class-specific base style. This
1998 * constructor of View allows subclasses to use their own base style when
1999 * they are inflating. For example, a Button class's constructor would call
2000 * this version of the super class constructor and supply
2001 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2002 * the theme's button style to modify all of the base view attributes (in
2003 * particular its background) as well as the Button class's attributes.
2004 *
2005 * @param context The Context the view is running in, through which it can
2006 * access the current theme, resources, etc.
2007 * @param attrs The attributes of the XML tag that is inflating the view.
2008 * @param defStyle The default style to apply to this view. If 0, no style
2009 * will be applied (beyond what is included in the theme). This may
2010 * either be an attribute resource, whose value will be retrieved
2011 * from the current theme, or an explicit style resource.
2012 * @see #View(Context, AttributeSet)
2013 */
2014 public View(Context context, AttributeSet attrs, int defStyle) {
2015 this(context);
2016
2017 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2018 defStyle, 0);
2019
2020 Drawable background = null;
2021
2022 int leftPadding = -1;
2023 int topPadding = -1;
2024 int rightPadding = -1;
2025 int bottomPadding = -1;
2026
2027 int padding = -1;
2028
2029 int viewFlagValues = 0;
2030 int viewFlagMasks = 0;
2031
2032 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 int x = 0;
2035 int y = 0;
2036
2037 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2038
2039 final int N = a.getIndexCount();
2040 for (int i = 0; i < N; i++) {
2041 int attr = a.getIndex(i);
2042 switch (attr) {
2043 case com.android.internal.R.styleable.View_background:
2044 background = a.getDrawable(attr);
2045 break;
2046 case com.android.internal.R.styleable.View_padding:
2047 padding = a.getDimensionPixelSize(attr, -1);
2048 break;
2049 case com.android.internal.R.styleable.View_paddingLeft:
2050 leftPadding = a.getDimensionPixelSize(attr, -1);
2051 break;
2052 case com.android.internal.R.styleable.View_paddingTop:
2053 topPadding = a.getDimensionPixelSize(attr, -1);
2054 break;
2055 case com.android.internal.R.styleable.View_paddingRight:
2056 rightPadding = a.getDimensionPixelSize(attr, -1);
2057 break;
2058 case com.android.internal.R.styleable.View_paddingBottom:
2059 bottomPadding = a.getDimensionPixelSize(attr, -1);
2060 break;
2061 case com.android.internal.R.styleable.View_scrollX:
2062 x = a.getDimensionPixelOffset(attr, 0);
2063 break;
2064 case com.android.internal.R.styleable.View_scrollY:
2065 y = a.getDimensionPixelOffset(attr, 0);
2066 break;
2067 case com.android.internal.R.styleable.View_id:
2068 mID = a.getResourceId(attr, NO_ID);
2069 break;
2070 case com.android.internal.R.styleable.View_tag:
2071 mTag = a.getText(attr);
2072 break;
2073 case com.android.internal.R.styleable.View_fitsSystemWindows:
2074 if (a.getBoolean(attr, false)) {
2075 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2076 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2077 }
2078 break;
2079 case com.android.internal.R.styleable.View_focusable:
2080 if (a.getBoolean(attr, false)) {
2081 viewFlagValues |= FOCUSABLE;
2082 viewFlagMasks |= FOCUSABLE_MASK;
2083 }
2084 break;
2085 case com.android.internal.R.styleable.View_focusableInTouchMode:
2086 if (a.getBoolean(attr, false)) {
2087 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2088 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2089 }
2090 break;
2091 case com.android.internal.R.styleable.View_clickable:
2092 if (a.getBoolean(attr, false)) {
2093 viewFlagValues |= CLICKABLE;
2094 viewFlagMasks |= CLICKABLE;
2095 }
2096 break;
2097 case com.android.internal.R.styleable.View_longClickable:
2098 if (a.getBoolean(attr, false)) {
2099 viewFlagValues |= LONG_CLICKABLE;
2100 viewFlagMasks |= LONG_CLICKABLE;
2101 }
2102 break;
2103 case com.android.internal.R.styleable.View_saveEnabled:
2104 if (!a.getBoolean(attr, true)) {
2105 viewFlagValues |= SAVE_DISABLED;
2106 viewFlagMasks |= SAVE_DISABLED_MASK;
2107 }
2108 break;
2109 case com.android.internal.R.styleable.View_duplicateParentState:
2110 if (a.getBoolean(attr, false)) {
2111 viewFlagValues |= DUPLICATE_PARENT_STATE;
2112 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2113 }
2114 break;
2115 case com.android.internal.R.styleable.View_visibility:
2116 final int visibility = a.getInt(attr, 0);
2117 if (visibility != 0) {
2118 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2119 viewFlagMasks |= VISIBILITY_MASK;
2120 }
2121 break;
2122 case com.android.internal.R.styleable.View_drawingCacheQuality:
2123 final int cacheQuality = a.getInt(attr, 0);
2124 if (cacheQuality != 0) {
2125 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2126 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2127 }
2128 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002129 case com.android.internal.R.styleable.View_contentDescription:
2130 mContentDescription = a.getString(attr);
2131 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2133 if (!a.getBoolean(attr, true)) {
2134 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2135 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2136 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002137 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2139 if (!a.getBoolean(attr, true)) {
2140 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2141 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2142 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002143 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 case R.styleable.View_scrollbars:
2145 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2146 if (scrollbars != SCROLLBARS_NONE) {
2147 viewFlagValues |= scrollbars;
2148 viewFlagMasks |= SCROLLBARS_MASK;
2149 initializeScrollbars(a);
2150 }
2151 break;
2152 case R.styleable.View_fadingEdge:
2153 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2154 if (fadingEdge != FADING_EDGE_NONE) {
2155 viewFlagValues |= fadingEdge;
2156 viewFlagMasks |= FADING_EDGE_MASK;
2157 initializeFadingEdge(a);
2158 }
2159 break;
2160 case R.styleable.View_scrollbarStyle:
2161 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2162 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2163 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2164 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2165 }
2166 break;
2167 case R.styleable.View_isScrollContainer:
2168 setScrollContainer = true;
2169 if (a.getBoolean(attr, false)) {
2170 setScrollContainer(true);
2171 }
2172 break;
2173 case com.android.internal.R.styleable.View_keepScreenOn:
2174 if (a.getBoolean(attr, false)) {
2175 viewFlagValues |= KEEP_SCREEN_ON;
2176 viewFlagMasks |= KEEP_SCREEN_ON;
2177 }
2178 break;
2179 case R.styleable.View_nextFocusLeft:
2180 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2181 break;
2182 case R.styleable.View_nextFocusRight:
2183 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2184 break;
2185 case R.styleable.View_nextFocusUp:
2186 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2187 break;
2188 case R.styleable.View_nextFocusDown:
2189 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2190 break;
2191 case R.styleable.View_minWidth:
2192 mMinWidth = a.getDimensionPixelSize(attr, 0);
2193 break;
2194 case R.styleable.View_minHeight:
2195 mMinHeight = a.getDimensionPixelSize(attr, 0);
2196 break;
Romain Guy9a817362009-05-01 10:57:14 -07002197 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002198 if (context.isRestricted()) {
2199 throw new IllegalStateException("The android:onClick attribute cannot "
2200 + "be used within a restricted context");
2201 }
2202
Romain Guy9a817362009-05-01 10:57:14 -07002203 final String handlerName = a.getString(attr);
2204 if (handlerName != null) {
2205 setOnClickListener(new OnClickListener() {
2206 private Method mHandler;
2207
2208 public void onClick(View v) {
2209 if (mHandler == null) {
2210 try {
2211 mHandler = getContext().getClass().getMethod(handlerName,
2212 View.class);
2213 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002214 int id = getId();
2215 String idText = id == NO_ID ? "" : " with id '"
2216 + getContext().getResources().getResourceEntryName(
2217 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002218 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002219 handlerName + "(View) in the activity "
2220 + getContext().getClass() + " for onClick handler"
2221 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002222 }
2223 }
2224
2225 try {
2226 mHandler.invoke(getContext(), View.this);
2227 } catch (IllegalAccessException e) {
2228 throw new IllegalStateException("Could not execute non "
2229 + "public method of the activity", e);
2230 } catch (InvocationTargetException e) {
2231 throw new IllegalStateException("Could not execute "
2232 + "method of the activity", e);
2233 }
2234 }
2235 });
2236 }
2237 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 }
2239 }
2240
2241 if (background != null) {
2242 setBackgroundDrawable(background);
2243 }
2244
2245 if (padding >= 0) {
2246 leftPadding = padding;
2247 topPadding = padding;
2248 rightPadding = padding;
2249 bottomPadding = padding;
2250 }
2251
2252 // If the user specified the padding (either with android:padding or
2253 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2254 // use the default padding or the padding from the background drawable
2255 // (stored at this point in mPadding*)
2256 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2257 topPadding >= 0 ? topPadding : mPaddingTop,
2258 rightPadding >= 0 ? rightPadding : mPaddingRight,
2259 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2260
2261 if (viewFlagMasks != 0) {
2262 setFlags(viewFlagValues, viewFlagMasks);
2263 }
2264
2265 // Needs to be called after mViewFlags is set
2266 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2267 recomputePadding();
2268 }
2269
2270 if (x != 0 || y != 0) {
2271 scrollTo(x, y);
2272 }
2273
2274 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2275 setScrollContainer(true);
2276 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002277
2278 computeOpaqueFlags();
2279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 a.recycle();
2281 }
2282
2283 /**
2284 * Non-public constructor for use in testing
2285 */
2286 View() {
2287 }
2288
Carl Shapiro82fe5642010-02-24 00:14:23 -08002289 // Used for debug only
2290 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 @Override
2292 protected void finalize() throws Throwable {
2293 super.finalize();
2294 --sInstanceCount;
2295 }
Carl Shapiro82fe5642010-02-24 00:14:23 -08002296 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297
2298 /**
2299 * <p>
2300 * Initializes the fading edges from a given set of styled attributes. This
2301 * method should be called by subclasses that need fading edges and when an
2302 * instance of these subclasses is created programmatically rather than
2303 * being inflated from XML. This method is automatically called when the XML
2304 * is inflated.
2305 * </p>
2306 *
2307 * @param a the styled attributes set to initialize the fading edges from
2308 */
2309 protected void initializeFadingEdge(TypedArray a) {
2310 initScrollCache();
2311
2312 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2313 R.styleable.View_fadingEdgeLength,
2314 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2315 }
2316
2317 /**
2318 * Returns the size of the vertical faded edges used to indicate that more
2319 * content in this view is visible.
2320 *
2321 * @return The size in pixels of the vertical faded edge or 0 if vertical
2322 * faded edges are not enabled for this view.
2323 * @attr ref android.R.styleable#View_fadingEdgeLength
2324 */
2325 public int getVerticalFadingEdgeLength() {
2326 if (isVerticalFadingEdgeEnabled()) {
2327 ScrollabilityCache cache = mScrollCache;
2328 if (cache != null) {
2329 return cache.fadingEdgeLength;
2330 }
2331 }
2332 return 0;
2333 }
2334
2335 /**
2336 * Set the size of the faded edge used to indicate that more content in this
2337 * view is available. Will not change whether the fading edge is enabled; use
2338 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2339 * to enable the fading edge for the vertical or horizontal fading edges.
2340 *
2341 * @param length The size in pixels of the faded edge used to indicate that more
2342 * content in this view is visible.
2343 */
2344 public void setFadingEdgeLength(int length) {
2345 initScrollCache();
2346 mScrollCache.fadingEdgeLength = length;
2347 }
2348
2349 /**
2350 * Returns the size of the horizontal faded edges used to indicate that more
2351 * content in this view is visible.
2352 *
2353 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2354 * faded edges are not enabled for this view.
2355 * @attr ref android.R.styleable#View_fadingEdgeLength
2356 */
2357 public int getHorizontalFadingEdgeLength() {
2358 if (isHorizontalFadingEdgeEnabled()) {
2359 ScrollabilityCache cache = mScrollCache;
2360 if (cache != null) {
2361 return cache.fadingEdgeLength;
2362 }
2363 }
2364 return 0;
2365 }
2366
2367 /**
2368 * Returns the width of the vertical scrollbar.
2369 *
2370 * @return The width in pixels of the vertical scrollbar or 0 if there
2371 * is no vertical scrollbar.
2372 */
2373 public int getVerticalScrollbarWidth() {
2374 ScrollabilityCache cache = mScrollCache;
2375 if (cache != null) {
2376 ScrollBarDrawable scrollBar = cache.scrollBar;
2377 if (scrollBar != null) {
2378 int size = scrollBar.getSize(true);
2379 if (size <= 0) {
2380 size = cache.scrollBarSize;
2381 }
2382 return size;
2383 }
2384 return 0;
2385 }
2386 return 0;
2387 }
2388
2389 /**
2390 * Returns the height of the horizontal scrollbar.
2391 *
2392 * @return The height in pixels of the horizontal scrollbar or 0 if
2393 * there is no horizontal scrollbar.
2394 */
2395 protected int getHorizontalScrollbarHeight() {
2396 ScrollabilityCache cache = mScrollCache;
2397 if (cache != null) {
2398 ScrollBarDrawable scrollBar = cache.scrollBar;
2399 if (scrollBar != null) {
2400 int size = scrollBar.getSize(false);
2401 if (size <= 0) {
2402 size = cache.scrollBarSize;
2403 }
2404 return size;
2405 }
2406 return 0;
2407 }
2408 return 0;
2409 }
2410
2411 /**
2412 * <p>
2413 * Initializes the scrollbars from a given set of styled attributes. This
2414 * method should be called by subclasses that need scrollbars and when an
2415 * instance of these subclasses is created programmatically rather than
2416 * being inflated from XML. This method is automatically called when the XML
2417 * is inflated.
2418 * </p>
2419 *
2420 * @param a the styled attributes set to initialize the scrollbars from
2421 */
2422 protected void initializeScrollbars(TypedArray a) {
2423 initScrollCache();
2424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002426
2427 if (scrollabilityCache.scrollBar == null) {
2428 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2429 }
2430
Romain Guy8bda2482010-03-02 11:42:11 -08002431 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432
Mike Cleronf116bf82009-09-27 19:14:12 -07002433 if (!fadeScrollbars) {
2434 scrollabilityCache.state = ScrollabilityCache.ON;
2435 }
2436 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2437
2438
2439 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2440 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2441 .getScrollBarFadeDuration());
2442 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2443 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2444 ViewConfiguration.getScrollDefaultDelay());
2445
2446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2448 com.android.internal.R.styleable.View_scrollbarSize,
2449 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2450
2451 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2452 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2453
2454 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2455 if (thumb != null) {
2456 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2457 }
2458
2459 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2460 false);
2461 if (alwaysDraw) {
2462 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2463 }
2464
2465 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2466 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2467
2468 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2469 if (thumb != null) {
2470 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2471 }
2472
2473 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2474 false);
2475 if (alwaysDraw) {
2476 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2477 }
2478
2479 // Re-apply user/background padding so that scrollbar(s) get added
2480 recomputePadding();
2481 }
2482
2483 /**
2484 * <p>
2485 * Initalizes the scrollability cache if necessary.
2486 * </p>
2487 */
2488 private void initScrollCache() {
2489 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002490 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 }
2492 }
2493
2494 /**
2495 * Register a callback to be invoked when focus of this view changed.
2496 *
2497 * @param l The callback that will run.
2498 */
2499 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2500 mOnFocusChangeListener = l;
2501 }
2502
2503 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002504 * Add a listener that will be called when the bounds of the view change due to
2505 * layout processing.
2506 *
2507 * @param listener The listener that will be called when layout bounds change.
2508 */
2509 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2510 if (mOnLayoutChangeListeners == null) {
2511 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2512 }
2513 mOnLayoutChangeListeners.add(listener);
2514 }
2515
2516 /**
2517 * Remove a listener for layout changes.
2518 *
2519 * @param listener The listener for layout bounds change.
2520 */
2521 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2522 if (mOnLayoutChangeListeners == null) {
2523 return;
2524 }
2525 mOnLayoutChangeListeners.remove(listener);
2526 }
2527
2528 /**
2529 * Gets the current list of listeners for layout changes.
2530 * @return
2531 */
2532 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2533 return mOnLayoutChangeListeners;
2534 }
2535
2536 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 * Returns the focus-change callback registered for this view.
2538 *
2539 * @return The callback, or null if one is not registered.
2540 */
2541 public OnFocusChangeListener getOnFocusChangeListener() {
2542 return mOnFocusChangeListener;
2543 }
2544
2545 /**
2546 * Register a callback to be invoked when this view is clicked. If this view is not
2547 * clickable, it becomes clickable.
2548 *
2549 * @param l The callback that will run
2550 *
2551 * @see #setClickable(boolean)
2552 */
2553 public void setOnClickListener(OnClickListener l) {
2554 if (!isClickable()) {
2555 setClickable(true);
2556 }
2557 mOnClickListener = l;
2558 }
2559
2560 /**
2561 * Register a callback to be invoked when this view is clicked and held. If this view is not
2562 * long clickable, it becomes long clickable.
2563 *
2564 * @param l The callback that will run
2565 *
2566 * @see #setLongClickable(boolean)
2567 */
2568 public void setOnLongClickListener(OnLongClickListener l) {
2569 if (!isLongClickable()) {
2570 setLongClickable(true);
2571 }
2572 mOnLongClickListener = l;
2573 }
2574
2575 /**
2576 * Register a callback to be invoked when the context menu for this view is
2577 * being built. If this view is not long clickable, it becomes long clickable.
2578 *
2579 * @param l The callback that will run
2580 *
2581 */
2582 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2583 if (!isLongClickable()) {
2584 setLongClickable(true);
2585 }
2586 mOnCreateContextMenuListener = l;
2587 }
2588
2589 /**
2590 * Call this view's OnClickListener, if it is defined.
2591 *
2592 * @return True there was an assigned OnClickListener that was called, false
2593 * otherwise is returned.
2594 */
2595 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002596 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 if (mOnClickListener != null) {
2599 playSoundEffect(SoundEffectConstants.CLICK);
2600 mOnClickListener.onClick(this);
2601 return true;
2602 }
2603
2604 return false;
2605 }
2606
2607 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002608 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2609 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002611 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 */
2613 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002614 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 boolean handled = false;
2617 if (mOnLongClickListener != null) {
2618 handled = mOnLongClickListener.onLongClick(View.this);
2619 }
2620 if (!handled) {
2621 handled = showContextMenu();
2622 }
2623 if (handled) {
2624 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2625 }
2626 return handled;
2627 }
2628
2629 /**
2630 * Bring up the context menu for this view.
2631 *
2632 * @return Whether a context menu was displayed.
2633 */
2634 public boolean showContextMenu() {
2635 return getParent().showContextMenuForChild(this);
2636 }
2637
2638 /**
Adam Powell6e346362010-07-23 10:18:23 -07002639 * Start an action mode.
2640 *
2641 * @param callback Callback that will control the lifecycle of the action mode
2642 * @return The new action mode if it is started, null otherwise
2643 *
2644 * @see ActionMode
2645 */
2646 public ActionMode startActionMode(ActionMode.Callback callback) {
2647 return getParent().startActionModeForChild(this, callback);
2648 }
2649
2650 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 * Register a callback to be invoked when a key is pressed in this view.
2652 * @param l the key listener to attach to this view
2653 */
2654 public void setOnKeyListener(OnKeyListener l) {
2655 mOnKeyListener = l;
2656 }
2657
2658 /**
2659 * Register a callback to be invoked when a touch event is sent to this view.
2660 * @param l the touch listener to attach to this view
2661 */
2662 public void setOnTouchListener(OnTouchListener l) {
2663 mOnTouchListener = l;
2664 }
2665
2666 /**
2667 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2668 *
2669 * Note: this does not check whether this {@link View} should get focus, it just
2670 * gives it focus no matter what. It should only be called internally by framework
2671 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2672 *
2673 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2674 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2675 * focus moved when requestFocus() is called. It may not always
2676 * apply, in which case use the default View.FOCUS_DOWN.
2677 * @param previouslyFocusedRect The rectangle of the view that had focus
2678 * prior in this View's coordinate system.
2679 */
2680 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2681 if (DBG) {
2682 System.out.println(this + " requestFocus()");
2683 }
2684
2685 if ((mPrivateFlags & FOCUSED) == 0) {
2686 mPrivateFlags |= FOCUSED;
2687
2688 if (mParent != null) {
2689 mParent.requestChildFocus(this, this);
2690 }
2691
2692 onFocusChanged(true, direction, previouslyFocusedRect);
2693 refreshDrawableState();
2694 }
2695 }
2696
2697 /**
2698 * Request that a rectangle of this view be visible on the screen,
2699 * scrolling if necessary just enough.
2700 *
2701 * <p>A View should call this if it maintains some notion of which part
2702 * of its content is interesting. For example, a text editing view
2703 * should call this when its cursor moves.
2704 *
2705 * @param rectangle The rectangle.
2706 * @return Whether any parent scrolled.
2707 */
2708 public boolean requestRectangleOnScreen(Rect rectangle) {
2709 return requestRectangleOnScreen(rectangle, false);
2710 }
2711
2712 /**
2713 * Request that a rectangle of this view be visible on the screen,
2714 * scrolling if necessary just enough.
2715 *
2716 * <p>A View should call this if it maintains some notion of which part
2717 * of its content is interesting. For example, a text editing view
2718 * should call this when its cursor moves.
2719 *
2720 * <p>When <code>immediate</code> is set to true, scrolling will not be
2721 * animated.
2722 *
2723 * @param rectangle The rectangle.
2724 * @param immediate True to forbid animated scrolling, false otherwise
2725 * @return Whether any parent scrolled.
2726 */
2727 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
2728 View child = this;
2729 ViewParent parent = mParent;
2730 boolean scrolled = false;
2731 while (parent != null) {
2732 scrolled |= parent.requestChildRectangleOnScreen(child,
2733 rectangle, immediate);
2734
2735 // offset rect so next call has the rectangle in the
2736 // coordinate system of its direct child.
2737 rectangle.offset(child.getLeft(), child.getTop());
2738 rectangle.offset(-child.getScrollX(), -child.getScrollY());
2739
2740 if (!(parent instanceof View)) {
2741 break;
2742 }
Romain Guy8506ab42009-06-11 17:35:47 -07002743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 child = (View) parent;
2745 parent = child.getParent();
2746 }
2747 return scrolled;
2748 }
2749
2750 /**
2751 * Called when this view wants to give up focus. This will cause
2752 * {@link #onFocusChanged} to be called.
2753 */
2754 public void clearFocus() {
2755 if (DBG) {
2756 System.out.println(this + " clearFocus()");
2757 }
2758
2759 if ((mPrivateFlags & FOCUSED) != 0) {
2760 mPrivateFlags &= ~FOCUSED;
2761
2762 if (mParent != null) {
2763 mParent.clearChildFocus(this);
2764 }
2765
2766 onFocusChanged(false, 0, null);
2767 refreshDrawableState();
2768 }
2769 }
2770
2771 /**
2772 * Called to clear the focus of a view that is about to be removed.
2773 * Doesn't call clearChildFocus, which prevents this view from taking
2774 * focus again before it has been removed from the parent
2775 */
2776 void clearFocusForRemoval() {
2777 if ((mPrivateFlags & FOCUSED) != 0) {
2778 mPrivateFlags &= ~FOCUSED;
2779
2780 onFocusChanged(false, 0, null);
2781 refreshDrawableState();
2782 }
2783 }
2784
2785 /**
2786 * Called internally by the view system when a new view is getting focus.
2787 * This is what clears the old focus.
2788 */
2789 void unFocus() {
2790 if (DBG) {
2791 System.out.println(this + " unFocus()");
2792 }
2793
2794 if ((mPrivateFlags & FOCUSED) != 0) {
2795 mPrivateFlags &= ~FOCUSED;
2796
2797 onFocusChanged(false, 0, null);
2798 refreshDrawableState();
2799 }
2800 }
2801
2802 /**
2803 * Returns true if this view has focus iteself, or is the ancestor of the
2804 * view that has focus.
2805 *
2806 * @return True if this view has or contains focus, false otherwise.
2807 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002808 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 public boolean hasFocus() {
2810 return (mPrivateFlags & FOCUSED) != 0;
2811 }
2812
2813 /**
2814 * Returns true if this view is focusable or if it contains a reachable View
2815 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
2816 * is a View whose parents do not block descendants focus.
2817 *
2818 * Only {@link #VISIBLE} views are considered focusable.
2819 *
2820 * @return True if the view is focusable or if the view contains a focusable
2821 * View, false otherwise.
2822 *
2823 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
2824 */
2825 public boolean hasFocusable() {
2826 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
2827 }
2828
2829 /**
2830 * Called by the view system when the focus state of this view changes.
2831 * When the focus change event is caused by directional navigation, direction
2832 * and previouslyFocusedRect provide insight into where the focus is coming from.
2833 * When overriding, be sure to call up through to the super class so that
2834 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07002835 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 * @param gainFocus True if the View has focus; false otherwise.
2837 * @param direction The direction focus has moved when requestFocus()
2838 * is called to give this view focus. Values are
Romain Guyea4823c2009-12-08 15:03:39 -08002839 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT} or
2840 * {@link #FOCUS_RIGHT}. It may not always apply, in which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 * case use the default.
2842 * @param previouslyFocusedRect The rectangle, in this view's coordinate
2843 * system, of the previously focused view. If applicable, this will be
2844 * passed in as finer grained information about where the focus is coming
2845 * from (in addition to direction). Will be <code>null</code> otherwise.
2846 */
2847 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07002848 if (gainFocus) {
2849 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2850 }
2851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 InputMethodManager imm = InputMethodManager.peekInstance();
2853 if (!gainFocus) {
2854 if (isPressed()) {
2855 setPressed(false);
2856 }
2857 if (imm != null && mAttachInfo != null
2858 && mAttachInfo.mHasWindowFocus) {
2859 imm.focusOut(this);
2860 }
Romain Guya2431d02009-04-30 16:30:00 -07002861 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 } else if (imm != null && mAttachInfo != null
2863 && mAttachInfo.mHasWindowFocus) {
2864 imm.focusIn(this);
2865 }
Romain Guy8506ab42009-06-11 17:35:47 -07002866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 invalidate();
2868 if (mOnFocusChangeListener != null) {
2869 mOnFocusChangeListener.onFocusChange(this, gainFocus);
2870 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002871
2872 if (mAttachInfo != null) {
2873 mAttachInfo.mKeyDispatchState.reset(this);
2874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 }
2876
2877 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002878 * {@inheritDoc}
2879 */
2880 public void sendAccessibilityEvent(int eventType) {
2881 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
2882 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
2883 }
2884 }
2885
2886 /**
2887 * {@inheritDoc}
2888 */
2889 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
2890 event.setClassName(getClass().getName());
2891 event.setPackageName(getContext().getPackageName());
2892 event.setEnabled(isEnabled());
2893 event.setContentDescription(mContentDescription);
2894
2895 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
2896 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
2897 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
2898 event.setItemCount(focusablesTempList.size());
2899 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
2900 focusablesTempList.clear();
2901 }
2902
2903 dispatchPopulateAccessibilityEvent(event);
2904
2905 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
2906 }
2907
2908 /**
2909 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
2910 * to be populated.
2911 *
2912 * @param event The event.
2913 *
2914 * @return True if the event population was completed.
2915 */
2916 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2917 return false;
2918 }
2919
2920 /**
2921 * Gets the {@link View} description. It briefly describes the view and is
2922 * primarily used for accessibility support. Set this property to enable
2923 * better accessibility support for your application. This is especially
2924 * true for views that do not have textual representation (For example,
2925 * ImageButton).
2926 *
2927 * @return The content descriptiopn.
2928 *
2929 * @attr ref android.R.styleable#View_contentDescription
2930 */
2931 public CharSequence getContentDescription() {
2932 return mContentDescription;
2933 }
2934
2935 /**
2936 * Sets the {@link View} description. It briefly describes the view and is
2937 * primarily used for accessibility support. Set this property to enable
2938 * better accessibility support for your application. This is especially
2939 * true for views that do not have textual representation (For example,
2940 * ImageButton).
2941 *
2942 * @param contentDescription The content description.
2943 *
2944 * @attr ref android.R.styleable#View_contentDescription
2945 */
2946 public void setContentDescription(CharSequence contentDescription) {
2947 mContentDescription = contentDescription;
2948 }
2949
2950 /**
Romain Guya2431d02009-04-30 16:30:00 -07002951 * Invoked whenever this view loses focus, either by losing window focus or by losing
2952 * focus within its window. This method can be used to clear any state tied to the
2953 * focus. For instance, if a button is held pressed with the trackball and the window
2954 * loses focus, this method can be used to cancel the press.
2955 *
2956 * Subclasses of View overriding this method should always call super.onFocusLost().
2957 *
2958 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07002959 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07002960 *
2961 * @hide pending API council approval
2962 */
2963 protected void onFocusLost() {
2964 resetPressedState();
2965 }
2966
2967 private void resetPressedState() {
2968 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
2969 return;
2970 }
2971
2972 if (isPressed()) {
2973 setPressed(false);
2974
2975 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05002976 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07002977 }
2978 }
2979 }
2980
2981 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 * Returns true if this view has focus
2983 *
2984 * @return True if this view has focus, false otherwise.
2985 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002986 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 public boolean isFocused() {
2988 return (mPrivateFlags & FOCUSED) != 0;
2989 }
2990
2991 /**
2992 * Find the view in the hierarchy rooted at this view that currently has
2993 * focus.
2994 *
2995 * @return The view that currently has focus, or null if no focused view can
2996 * be found.
2997 */
2998 public View findFocus() {
2999 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3000 }
3001
3002 /**
3003 * Change whether this view is one of the set of scrollable containers in
3004 * its window. This will be used to determine whether the window can
3005 * resize or must pan when a soft input area is open -- scrollable
3006 * containers allow the window to use resize mode since the container
3007 * will appropriately shrink.
3008 */
3009 public void setScrollContainer(boolean isScrollContainer) {
3010 if (isScrollContainer) {
3011 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3012 mAttachInfo.mScrollContainers.add(this);
3013 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3014 }
3015 mPrivateFlags |= SCROLL_CONTAINER;
3016 } else {
3017 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3018 mAttachInfo.mScrollContainers.remove(this);
3019 }
3020 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3021 }
3022 }
3023
3024 /**
3025 * Returns the quality of the drawing cache.
3026 *
3027 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3028 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3029 *
3030 * @see #setDrawingCacheQuality(int)
3031 * @see #setDrawingCacheEnabled(boolean)
3032 * @see #isDrawingCacheEnabled()
3033 *
3034 * @attr ref android.R.styleable#View_drawingCacheQuality
3035 */
3036 public int getDrawingCacheQuality() {
3037 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3038 }
3039
3040 /**
3041 * Set the drawing cache quality of this view. This value is used only when the
3042 * drawing cache is enabled
3043 *
3044 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3045 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3046 *
3047 * @see #getDrawingCacheQuality()
3048 * @see #setDrawingCacheEnabled(boolean)
3049 * @see #isDrawingCacheEnabled()
3050 *
3051 * @attr ref android.R.styleable#View_drawingCacheQuality
3052 */
3053 public void setDrawingCacheQuality(int quality) {
3054 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3055 }
3056
3057 /**
3058 * Returns whether the screen should remain on, corresponding to the current
3059 * value of {@link #KEEP_SCREEN_ON}.
3060 *
3061 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3062 *
3063 * @see #setKeepScreenOn(boolean)
3064 *
3065 * @attr ref android.R.styleable#View_keepScreenOn
3066 */
3067 public boolean getKeepScreenOn() {
3068 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3069 }
3070
3071 /**
3072 * Controls whether the screen should remain on, modifying the
3073 * value of {@link #KEEP_SCREEN_ON}.
3074 *
3075 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3076 *
3077 * @see #getKeepScreenOn()
3078 *
3079 * @attr ref android.R.styleable#View_keepScreenOn
3080 */
3081 public void setKeepScreenOn(boolean keepScreenOn) {
3082 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3083 }
3084
3085 /**
3086 * @return The user specified next focus ID.
3087 *
3088 * @attr ref android.R.styleable#View_nextFocusLeft
3089 */
3090 public int getNextFocusLeftId() {
3091 return mNextFocusLeftId;
3092 }
3093
3094 /**
3095 * Set the id of the view to use for the next focus
3096 *
3097 * @param nextFocusLeftId
3098 *
3099 * @attr ref android.R.styleable#View_nextFocusLeft
3100 */
3101 public void setNextFocusLeftId(int nextFocusLeftId) {
3102 mNextFocusLeftId = nextFocusLeftId;
3103 }
3104
3105 /**
3106 * @return The user specified next focus ID.
3107 *
3108 * @attr ref android.R.styleable#View_nextFocusRight
3109 */
3110 public int getNextFocusRightId() {
3111 return mNextFocusRightId;
3112 }
3113
3114 /**
3115 * Set the id of the view to use for the next focus
3116 *
3117 * @param nextFocusRightId
3118 *
3119 * @attr ref android.R.styleable#View_nextFocusRight
3120 */
3121 public void setNextFocusRightId(int nextFocusRightId) {
3122 mNextFocusRightId = nextFocusRightId;
3123 }
3124
3125 /**
3126 * @return The user specified next focus ID.
3127 *
3128 * @attr ref android.R.styleable#View_nextFocusUp
3129 */
3130 public int getNextFocusUpId() {
3131 return mNextFocusUpId;
3132 }
3133
3134 /**
3135 * Set the id of the view to use for the next focus
3136 *
3137 * @param nextFocusUpId
3138 *
3139 * @attr ref android.R.styleable#View_nextFocusUp
3140 */
3141 public void setNextFocusUpId(int nextFocusUpId) {
3142 mNextFocusUpId = nextFocusUpId;
3143 }
3144
3145 /**
3146 * @return The user specified next focus ID.
3147 *
3148 * @attr ref android.R.styleable#View_nextFocusDown
3149 */
3150 public int getNextFocusDownId() {
3151 return mNextFocusDownId;
3152 }
3153
3154 /**
3155 * Set the id of the view to use for the next focus
3156 *
3157 * @param nextFocusDownId
3158 *
3159 * @attr ref android.R.styleable#View_nextFocusDown
3160 */
3161 public void setNextFocusDownId(int nextFocusDownId) {
3162 mNextFocusDownId = nextFocusDownId;
3163 }
3164
3165 /**
3166 * Returns the visibility of this view and all of its ancestors
3167 *
3168 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3169 */
3170 public boolean isShown() {
3171 View current = this;
3172 //noinspection ConstantConditions
3173 do {
3174 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3175 return false;
3176 }
3177 ViewParent parent = current.mParent;
3178 if (parent == null) {
3179 return false; // We are not attached to the view root
3180 }
3181 if (!(parent instanceof View)) {
3182 return true;
3183 }
3184 current = (View) parent;
3185 } while (current != null);
3186
3187 return false;
3188 }
3189
3190 /**
3191 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3192 * is set
3193 *
3194 * @param insets Insets for system windows
3195 *
3196 * @return True if this view applied the insets, false otherwise
3197 */
3198 protected boolean fitSystemWindows(Rect insets) {
3199 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3200 mPaddingLeft = insets.left;
3201 mPaddingTop = insets.top;
3202 mPaddingRight = insets.right;
3203 mPaddingBottom = insets.bottom;
3204 requestLayout();
3205 return true;
3206 }
3207 return false;
3208 }
3209
3210 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003211 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3212 * @return True if window has FITS_SYSTEM_WINDOWS set
3213 *
3214 * @hide
3215 */
3216 public boolean isFitsSystemWindowsFlagSet() {
3217 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3218 }
3219
3220 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 * Returns the visibility status for this view.
3222 *
3223 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3224 * @attr ref android.R.styleable#View_visibility
3225 */
3226 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003227 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3228 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3229 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 })
3231 public int getVisibility() {
3232 return mViewFlags & VISIBILITY_MASK;
3233 }
3234
3235 /**
3236 * Set the enabled state of this view.
3237 *
3238 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3239 * @attr ref android.R.styleable#View_visibility
3240 */
3241 @RemotableViewMethod
3242 public void setVisibility(int visibility) {
3243 setFlags(visibility, VISIBILITY_MASK);
3244 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3245 }
3246
3247 /**
3248 * Returns the enabled status for this view. The interpretation of the
3249 * enabled state varies by subclass.
3250 *
3251 * @return True if this view is enabled, false otherwise.
3252 */
3253 @ViewDebug.ExportedProperty
3254 public boolean isEnabled() {
3255 return (mViewFlags & ENABLED_MASK) == ENABLED;
3256 }
3257
3258 /**
3259 * Set the enabled state of this view. The interpretation of the enabled
3260 * state varies by subclass.
3261 *
3262 * @param enabled True if this view is enabled, false otherwise.
3263 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003264 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003266 if (enabled == isEnabled()) return;
3267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3269
3270 /*
3271 * The View most likely has to change its appearance, so refresh
3272 * the drawable state.
3273 */
3274 refreshDrawableState();
3275
3276 // Invalidate too, since the default behavior for views is to be
3277 // be drawn at 50% alpha rather than to change the drawable.
3278 invalidate();
3279 }
3280
3281 /**
3282 * Set whether this view can receive the focus.
3283 *
3284 * Setting this to false will also ensure that this view is not focusable
3285 * in touch mode.
3286 *
3287 * @param focusable If true, this view can receive the focus.
3288 *
3289 * @see #setFocusableInTouchMode(boolean)
3290 * @attr ref android.R.styleable#View_focusable
3291 */
3292 public void setFocusable(boolean focusable) {
3293 if (!focusable) {
3294 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3295 }
3296 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3297 }
3298
3299 /**
3300 * Set whether this view can receive focus while in touch mode.
3301 *
3302 * Setting this to true will also ensure that this view is focusable.
3303 *
3304 * @param focusableInTouchMode If true, this view can receive the focus while
3305 * in touch mode.
3306 *
3307 * @see #setFocusable(boolean)
3308 * @attr ref android.R.styleable#View_focusableInTouchMode
3309 */
3310 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3311 // Focusable in touch mode should always be set before the focusable flag
3312 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3313 // which, in touch mode, will not successfully request focus on this view
3314 // because the focusable in touch mode flag is not set
3315 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3316 if (focusableInTouchMode) {
3317 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3318 }
3319 }
3320
3321 /**
3322 * Set whether this view should have sound effects enabled for events such as
3323 * clicking and touching.
3324 *
3325 * <p>You may wish to disable sound effects for a view if you already play sounds,
3326 * for instance, a dial key that plays dtmf tones.
3327 *
3328 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3329 * @see #isSoundEffectsEnabled()
3330 * @see #playSoundEffect(int)
3331 * @attr ref android.R.styleable#View_soundEffectsEnabled
3332 */
3333 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3334 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3335 }
3336
3337 /**
3338 * @return whether this view should have sound effects enabled for events such as
3339 * clicking and touching.
3340 *
3341 * @see #setSoundEffectsEnabled(boolean)
3342 * @see #playSoundEffect(int)
3343 * @attr ref android.R.styleable#View_soundEffectsEnabled
3344 */
3345 @ViewDebug.ExportedProperty
3346 public boolean isSoundEffectsEnabled() {
3347 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3348 }
3349
3350 /**
3351 * Set whether this view should have haptic feedback for events such as
3352 * long presses.
3353 *
3354 * <p>You may wish to disable haptic feedback if your view already controls
3355 * its own haptic feedback.
3356 *
3357 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3358 * @see #isHapticFeedbackEnabled()
3359 * @see #performHapticFeedback(int)
3360 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3361 */
3362 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3363 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3364 }
3365
3366 /**
3367 * @return whether this view should have haptic feedback enabled for events
3368 * long presses.
3369 *
3370 * @see #setHapticFeedbackEnabled(boolean)
3371 * @see #performHapticFeedback(int)
3372 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3373 */
3374 @ViewDebug.ExportedProperty
3375 public boolean isHapticFeedbackEnabled() {
3376 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3377 }
3378
3379 /**
3380 * If this view doesn't do any drawing on its own, set this flag to
3381 * allow further optimizations. By default, this flag is not set on
3382 * View, but could be set on some View subclasses such as ViewGroup.
3383 *
3384 * Typically, if you override {@link #onDraw} you should clear this flag.
3385 *
3386 * @param willNotDraw whether or not this View draw on its own
3387 */
3388 public void setWillNotDraw(boolean willNotDraw) {
3389 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3390 }
3391
3392 /**
3393 * Returns whether or not this View draws on its own.
3394 *
3395 * @return true if this view has nothing to draw, false otherwise
3396 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003397 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 public boolean willNotDraw() {
3399 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3400 }
3401
3402 /**
3403 * When a View's drawing cache is enabled, drawing is redirected to an
3404 * offscreen bitmap. Some views, like an ImageView, must be able to
3405 * bypass this mechanism if they already draw a single bitmap, to avoid
3406 * unnecessary usage of the memory.
3407 *
3408 * @param willNotCacheDrawing true if this view does not cache its
3409 * drawing, false otherwise
3410 */
3411 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3412 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3413 }
3414
3415 /**
3416 * Returns whether or not this View can cache its drawing or not.
3417 *
3418 * @return true if this view does not cache its drawing, false otherwise
3419 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003420 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 public boolean willNotCacheDrawing() {
3422 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3423 }
3424
3425 /**
3426 * Indicates whether this view reacts to click events or not.
3427 *
3428 * @return true if the view is clickable, false otherwise
3429 *
3430 * @see #setClickable(boolean)
3431 * @attr ref android.R.styleable#View_clickable
3432 */
3433 @ViewDebug.ExportedProperty
3434 public boolean isClickable() {
3435 return (mViewFlags & CLICKABLE) == CLICKABLE;
3436 }
3437
3438 /**
3439 * Enables or disables click events for this view. When a view
3440 * is clickable it will change its state to "pressed" on every click.
3441 * Subclasses should set the view clickable to visually react to
3442 * user's clicks.
3443 *
3444 * @param clickable true to make the view clickable, false otherwise
3445 *
3446 * @see #isClickable()
3447 * @attr ref android.R.styleable#View_clickable
3448 */
3449 public void setClickable(boolean clickable) {
3450 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3451 }
3452
3453 /**
3454 * Indicates whether this view reacts to long click events or not.
3455 *
3456 * @return true if the view is long clickable, false otherwise
3457 *
3458 * @see #setLongClickable(boolean)
3459 * @attr ref android.R.styleable#View_longClickable
3460 */
3461 public boolean isLongClickable() {
3462 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3463 }
3464
3465 /**
3466 * Enables or disables long click events for this view. When a view is long
3467 * clickable it reacts to the user holding down the button for a longer
3468 * duration than a tap. This event can either launch the listener or a
3469 * context menu.
3470 *
3471 * @param longClickable true to make the view long clickable, false otherwise
3472 * @see #isLongClickable()
3473 * @attr ref android.R.styleable#View_longClickable
3474 */
3475 public void setLongClickable(boolean longClickable) {
3476 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3477 }
3478
3479 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003480 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 *
3482 * @see #isClickable()
3483 * @see #setClickable(boolean)
3484 *
3485 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3486 * the View's internal state from a previously set "pressed" state.
3487 */
3488 public void setPressed(boolean pressed) {
3489 if (pressed) {
3490 mPrivateFlags |= PRESSED;
3491 } else {
3492 mPrivateFlags &= ~PRESSED;
3493 }
3494 refreshDrawableState();
3495 dispatchSetPressed(pressed);
3496 }
3497
3498 /**
3499 * Dispatch setPressed to all of this View's children.
3500 *
3501 * @see #setPressed(boolean)
3502 *
3503 * @param pressed The new pressed state
3504 */
3505 protected void dispatchSetPressed(boolean pressed) {
3506 }
3507
3508 /**
3509 * Indicates whether the view is currently in pressed state. Unless
3510 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3511 * the pressed state.
3512 *
3513 * @see #setPressed
3514 * @see #isClickable()
3515 * @see #setClickable(boolean)
3516 *
3517 * @return true if the view is currently pressed, false otherwise
3518 */
3519 public boolean isPressed() {
3520 return (mPrivateFlags & PRESSED) == PRESSED;
3521 }
3522
3523 /**
3524 * Indicates whether this view will save its state (that is,
3525 * whether its {@link #onSaveInstanceState} method will be called).
3526 *
3527 * @return Returns true if the view state saving is enabled, else false.
3528 *
3529 * @see #setSaveEnabled(boolean)
3530 * @attr ref android.R.styleable#View_saveEnabled
3531 */
3532 public boolean isSaveEnabled() {
3533 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3534 }
3535
3536 /**
3537 * Controls whether the saving of this view's state is
3538 * enabled (that is, whether its {@link #onSaveInstanceState} method
3539 * will be called). Note that even if freezing is enabled, the
3540 * view still must have an id assigned to it (via {@link #setId setId()})
3541 * for its state to be saved. This flag can only disable the
3542 * saving of this view; any child views may still have their state saved.
3543 *
3544 * @param enabled Set to false to <em>disable</em> state saving, or true
3545 * (the default) to allow it.
3546 *
3547 * @see #isSaveEnabled()
3548 * @see #setId(int)
3549 * @see #onSaveInstanceState()
3550 * @attr ref android.R.styleable#View_saveEnabled
3551 */
3552 public void setSaveEnabled(boolean enabled) {
3553 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3554 }
3555
3556
3557 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003558 * Indicates whether the entire hierarchy under this view will save its
3559 * state when a state saving traversal occurs from its parent. The default
3560 * is true; if false, these views will not be saved unless
3561 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3562 *
3563 * @return Returns true if the view state saving from parent is enabled, else false.
3564 *
3565 * @see #setSaveFromParentEnabled(boolean)
3566 */
3567 public boolean isSaveFromParentEnabled() {
3568 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3569 }
3570
3571 /**
3572 * Controls whether the entire hierarchy under this view will save its
3573 * state when a state saving traversal occurs from its parent. The default
3574 * is true; if false, these views will not be saved unless
3575 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3576 *
3577 * @param enabled Set to false to <em>disable</em> state saving, or true
3578 * (the default) to allow it.
3579 *
3580 * @see #isSaveFromParentEnabled()
3581 * @see #setId(int)
3582 * @see #onSaveInstanceState()
3583 */
3584 public void setSaveFromParentEnabled(boolean enabled) {
3585 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
3586 }
3587
3588
3589 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003590 * Returns whether this View is able to take focus.
3591 *
3592 * @return True if this view can take focus, or false otherwise.
3593 * @attr ref android.R.styleable#View_focusable
3594 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003595 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 public final boolean isFocusable() {
3597 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3598 }
3599
3600 /**
3601 * When a view is focusable, it may not want to take focus when in touch mode.
3602 * For example, a button would like focus when the user is navigating via a D-pad
3603 * so that the user can click on it, but once the user starts touching the screen,
3604 * the button shouldn't take focus
3605 * @return Whether the view is focusable in touch mode.
3606 * @attr ref android.R.styleable#View_focusableInTouchMode
3607 */
3608 @ViewDebug.ExportedProperty
3609 public final boolean isFocusableInTouchMode() {
3610 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3611 }
3612
3613 /**
3614 * Find the nearest view in the specified direction that can take focus.
3615 * This does not actually give focus to that view.
3616 *
3617 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3618 *
3619 * @return The nearest focusable in the specified direction, or null if none
3620 * can be found.
3621 */
3622 public View focusSearch(int direction) {
3623 if (mParent != null) {
3624 return mParent.focusSearch(this, direction);
3625 } else {
3626 return null;
3627 }
3628 }
3629
3630 /**
3631 * This method is the last chance for the focused view and its ancestors to
3632 * respond to an arrow key. This is called when the focused view did not
3633 * consume the key internally, nor could the view system find a new view in
3634 * the requested direction to give focus to.
3635 *
3636 * @param focused The currently focused view.
3637 * @param direction The direction focus wants to move. One of FOCUS_UP,
3638 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3639 * @return True if the this view consumed this unhandled move.
3640 */
3641 public boolean dispatchUnhandledMove(View focused, int direction) {
3642 return false;
3643 }
3644
3645 /**
3646 * If a user manually specified the next view id for a particular direction,
3647 * use the root to look up the view. Once a view is found, it is cached
3648 * for future lookups.
3649 * @param root The root view of the hierarchy containing this view.
3650 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3651 * @return The user specified next view, or null if there is none.
3652 */
3653 View findUserSetNextFocus(View root, int direction) {
3654 switch (direction) {
3655 case FOCUS_LEFT:
3656 if (mNextFocusLeftId == View.NO_ID) return null;
3657 return findViewShouldExist(root, mNextFocusLeftId);
3658 case FOCUS_RIGHT:
3659 if (mNextFocusRightId == View.NO_ID) return null;
3660 return findViewShouldExist(root, mNextFocusRightId);
3661 case FOCUS_UP:
3662 if (mNextFocusUpId == View.NO_ID) return null;
3663 return findViewShouldExist(root, mNextFocusUpId);
3664 case FOCUS_DOWN:
3665 if (mNextFocusDownId == View.NO_ID) return null;
3666 return findViewShouldExist(root, mNextFocusDownId);
3667 }
3668 return null;
3669 }
3670
3671 private static View findViewShouldExist(View root, int childViewId) {
3672 View result = root.findViewById(childViewId);
3673 if (result == null) {
3674 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
3675 + "by user for id " + childViewId);
3676 }
3677 return result;
3678 }
3679
3680 /**
3681 * Find and return all focusable views that are descendants of this view,
3682 * possibly including this view if it is focusable itself.
3683 *
3684 * @param direction The direction of the focus
3685 * @return A list of focusable views
3686 */
3687 public ArrayList<View> getFocusables(int direction) {
3688 ArrayList<View> result = new ArrayList<View>(24);
3689 addFocusables(result, direction);
3690 return result;
3691 }
3692
3693 /**
3694 * Add any focusable views that are descendants of this view (possibly
3695 * including this view if it is focusable itself) to views. If we are in touch mode,
3696 * only add views that are also focusable in touch mode.
3697 *
3698 * @param views Focusable views found so far
3699 * @param direction The direction of the focus
3700 */
3701 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003702 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
3703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704
svetoslavganov75986cf2009-05-14 22:28:01 -07003705 /**
3706 * Adds any focusable views that are descendants of this view (possibly
3707 * including this view if it is focusable itself) to views. This method
3708 * adds all focusable views regardless if we are in touch mode or
3709 * only views focusable in touch mode if we are in touch mode depending on
3710 * the focusable mode paramater.
3711 *
3712 * @param views Focusable views found so far or null if all we are interested is
3713 * the number of focusables.
3714 * @param direction The direction of the focus.
3715 * @param focusableMode The type of focusables to be added.
3716 *
3717 * @see #FOCUSABLES_ALL
3718 * @see #FOCUSABLES_TOUCH_MODE
3719 */
3720 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
3721 if (!isFocusable()) {
3722 return;
3723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724
svetoslavganov75986cf2009-05-14 22:28:01 -07003725 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
3726 isInTouchMode() && !isFocusableInTouchMode()) {
3727 return;
3728 }
3729
3730 if (views != null) {
3731 views.add(this);
3732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 }
3734
3735 /**
3736 * Find and return all touchable views that are descendants of this view,
3737 * possibly including this view if it is touchable itself.
3738 *
3739 * @return A list of touchable views
3740 */
3741 public ArrayList<View> getTouchables() {
3742 ArrayList<View> result = new ArrayList<View>();
3743 addTouchables(result);
3744 return result;
3745 }
3746
3747 /**
3748 * Add any touchable views that are descendants of this view (possibly
3749 * including this view if it is touchable itself) to views.
3750 *
3751 * @param views Touchable views found so far
3752 */
3753 public void addTouchables(ArrayList<View> views) {
3754 final int viewFlags = mViewFlags;
3755
3756 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
3757 && (viewFlags & ENABLED_MASK) == ENABLED) {
3758 views.add(this);
3759 }
3760 }
3761
3762 /**
3763 * Call this to try to give focus to a specific view or to one of its
3764 * descendants.
3765 *
3766 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3767 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3768 * while the device is in touch mode.
3769 *
3770 * See also {@link #focusSearch}, which is what you call to say that you
3771 * have focus, and you want your parent to look for the next one.
3772 *
3773 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
3774 * {@link #FOCUS_DOWN} and <code>null</code>.
3775 *
3776 * @return Whether this view or one of its descendants actually took focus.
3777 */
3778 public final boolean requestFocus() {
3779 return requestFocus(View.FOCUS_DOWN);
3780 }
3781
3782
3783 /**
3784 * Call this to try to give focus to a specific view or to one of its
3785 * descendants and give it a hint about what direction focus is heading.
3786 *
3787 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3788 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3789 * while the device is in touch mode.
3790 *
3791 * See also {@link #focusSearch}, which is what you call to say that you
3792 * have focus, and you want your parent to look for the next one.
3793 *
3794 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
3795 * <code>null</code> set for the previously focused rectangle.
3796 *
3797 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3798 * @return Whether this view or one of its descendants actually took focus.
3799 */
3800 public final boolean requestFocus(int direction) {
3801 return requestFocus(direction, null);
3802 }
3803
3804 /**
3805 * Call this to try to give focus to a specific view or to one of its descendants
3806 * and give it hints about the direction and a specific rectangle that the focus
3807 * is coming from. The rectangle can help give larger views a finer grained hint
3808 * about where focus is coming from, and therefore, where to show selection, or
3809 * forward focus change internally.
3810 *
3811 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3812 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3813 * while the device is in touch mode.
3814 *
3815 * A View will not take focus if it is not visible.
3816 *
3817 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
3818 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
3819 *
3820 * See also {@link #focusSearch}, which is what you call to say that you
3821 * have focus, and you want your parent to look for the next one.
3822 *
3823 * You may wish to override this method if your custom {@link View} has an internal
3824 * {@link View} that it wishes to forward the request to.
3825 *
3826 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3827 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
3828 * to give a finer grained hint about where focus is coming from. May be null
3829 * if there is no hint.
3830 * @return Whether this view or one of its descendants actually took focus.
3831 */
3832 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
3833 // need to be focusable
3834 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
3835 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3836 return false;
3837 }
3838
3839 // need to be focusable in touch mode if in touch mode
3840 if (isInTouchMode() &&
3841 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
3842 return false;
3843 }
3844
3845 // need to not have any parents blocking us
3846 if (hasAncestorThatBlocksDescendantFocus()) {
3847 return false;
3848 }
3849
3850 handleFocusGainInternal(direction, previouslyFocusedRect);
3851 return true;
3852 }
3853
3854 /**
3855 * Call this to try to give focus to a specific view or to one of its descendants. This is a
3856 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
3857 * touch mode to request focus when they are touched.
3858 *
3859 * @return Whether this view or one of its descendants actually took focus.
3860 *
3861 * @see #isInTouchMode()
3862 *
3863 */
3864 public final boolean requestFocusFromTouch() {
3865 // Leave touch mode if we need to
3866 if (isInTouchMode()) {
3867 View root = getRootView();
3868 if (root != null) {
3869 ViewRoot viewRoot = (ViewRoot)root.getParent();
3870 if (viewRoot != null) {
3871 viewRoot.ensureTouchMode(false);
3872 }
3873 }
3874 }
3875 return requestFocus(View.FOCUS_DOWN);
3876 }
3877
3878 /**
3879 * @return Whether any ancestor of this view blocks descendant focus.
3880 */
3881 private boolean hasAncestorThatBlocksDescendantFocus() {
3882 ViewParent ancestor = mParent;
3883 while (ancestor instanceof ViewGroup) {
3884 final ViewGroup vgAncestor = (ViewGroup) ancestor;
3885 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
3886 return true;
3887 } else {
3888 ancestor = vgAncestor.getParent();
3889 }
3890 }
3891 return false;
3892 }
3893
3894 /**
Romain Guya440b002010-02-24 15:57:54 -08003895 * @hide
3896 */
3897 public void dispatchStartTemporaryDetach() {
3898 onStartTemporaryDetach();
3899 }
3900
3901 /**
3902 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
3904 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08003905 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 */
3907 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08003908 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08003909 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08003910 }
3911
3912 /**
3913 * @hide
3914 */
3915 public void dispatchFinishTemporaryDetach() {
3916 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 }
Romain Guy8506ab42009-06-11 17:35:47 -07003918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 /**
3920 * Called after {@link #onStartTemporaryDetach} when the container is done
3921 * changing the view.
3922 */
3923 public void onFinishTemporaryDetach() {
3924 }
Romain Guy8506ab42009-06-11 17:35:47 -07003925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 /**
3927 * capture information of this view for later analysis: developement only
3928 * check dynamic switch to make sure we only dump view
3929 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
3930 */
3931 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003932 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 return;
3934 }
3935 ViewDebug.dumpCapturedView(subTag, v);
3936 }
3937
3938 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003939 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
3940 * for this view's window. Returns null if the view is not currently attached
3941 * to the window. Normally you will not need to use this directly, but
3942 * just use the standard high-level event callbacks like {@link #onKeyDown}.
3943 */
3944 public KeyEvent.DispatcherState getKeyDispatcherState() {
3945 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
3946 }
3947
3948 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 * Dispatch a key event before it is processed by any input method
3950 * associated with the view hierarchy. This can be used to intercept
3951 * key events in special situations before the IME consumes them; a
3952 * typical example would be handling the BACK key to update the application's
3953 * UI instead of allowing the IME to see it and close itself.
3954 *
3955 * @param event The key event to be dispatched.
3956 * @return True if the event was handled, false otherwise.
3957 */
3958 public boolean dispatchKeyEventPreIme(KeyEvent event) {
3959 return onKeyPreIme(event.getKeyCode(), event);
3960 }
3961
3962 /**
3963 * Dispatch a key event to the next view on the focus path. This path runs
3964 * from the top of the view tree down to the currently focused view. If this
3965 * view has focus, it will dispatch to itself. Otherwise it will dispatch
3966 * the next node down the focus path. This method also fires any key
3967 * listeners.
3968 *
3969 * @param event The key event to be dispatched.
3970 * @return True if the event was handled, false otherwise.
3971 */
3972 public boolean dispatchKeyEvent(KeyEvent event) {
3973 // If any attached key listener a first crack at the event.
3974 //noinspection SimplifiableIfStatement
3975
3976 if (android.util.Config.LOGV) {
3977 captureViewInfo("captureViewKeyEvent", this);
3978 }
3979
3980 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
3981 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
3982 return true;
3983 }
3984
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003985 return event.dispatch(this, mAttachInfo != null
3986 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 }
3988
3989 /**
3990 * Dispatches a key shortcut event.
3991 *
3992 * @param event The key event to be dispatched.
3993 * @return True if the event was handled by the view, false otherwise.
3994 */
3995 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
3996 return onKeyShortcut(event.getKeyCode(), event);
3997 }
3998
3999 /**
4000 * Pass the touch screen motion event down to the target view, or this
4001 * view if it is the target.
4002 *
4003 * @param event The motion event to be dispatched.
4004 * @return True if the event was handled by the view, false otherwise.
4005 */
4006 public boolean dispatchTouchEvent(MotionEvent event) {
4007 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4008 mOnTouchListener.onTouch(this, event)) {
4009 return true;
4010 }
4011 return onTouchEvent(event);
4012 }
4013
4014 /**
4015 * Pass a trackball motion event down to the focused view.
4016 *
4017 * @param event The motion event to be dispatched.
4018 * @return True if the event was handled by the view, false otherwise.
4019 */
4020 public boolean dispatchTrackballEvent(MotionEvent event) {
4021 //Log.i("view", "view=" + this + ", " + event.toString());
4022 return onTrackballEvent(event);
4023 }
4024
4025 /**
4026 * Called when the window containing this view gains or loses window focus.
4027 * ViewGroups should override to route to their children.
4028 *
4029 * @param hasFocus True if the window containing this view now has focus,
4030 * false otherwise.
4031 */
4032 public void dispatchWindowFocusChanged(boolean hasFocus) {
4033 onWindowFocusChanged(hasFocus);
4034 }
4035
4036 /**
4037 * Called when the window containing this view gains or loses focus. Note
4038 * that this is separate from view focus: to receive key events, both
4039 * your view and its window must have focus. If a window is displayed
4040 * on top of yours that takes input focus, then your own window will lose
4041 * focus but the view focus will remain unchanged.
4042 *
4043 * @param hasWindowFocus True if the window containing this view now has
4044 * focus, false otherwise.
4045 */
4046 public void onWindowFocusChanged(boolean hasWindowFocus) {
4047 InputMethodManager imm = InputMethodManager.peekInstance();
4048 if (!hasWindowFocus) {
4049 if (isPressed()) {
4050 setPressed(false);
4051 }
4052 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4053 imm.focusOut(this);
4054 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004055 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004056 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4058 imm.focusIn(this);
4059 }
4060 refreshDrawableState();
4061 }
4062
4063 /**
4064 * Returns true if this view is in a window that currently has window focus.
4065 * Note that this is not the same as the view itself having focus.
4066 *
4067 * @return True if this view is in a window that currently has window focus.
4068 */
4069 public boolean hasWindowFocus() {
4070 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4071 }
4072
4073 /**
Adam Powell326d8082009-12-09 15:10:07 -08004074 * Dispatch a view visibility change down the view hierarchy.
4075 * ViewGroups should override to route to their children.
4076 * @param changedView The view whose visibility changed. Could be 'this' or
4077 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004078 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4079 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004080 */
4081 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4082 onVisibilityChanged(changedView, visibility);
4083 }
4084
4085 /**
4086 * Called when the visibility of the view or an ancestor of the view is changed.
4087 * @param changedView The view whose visibility changed. Could be 'this' or
4088 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004089 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4090 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004091 */
4092 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004093 if (visibility == VISIBLE) {
4094 if (mAttachInfo != null) {
4095 initialAwakenScrollBars();
4096 } else {
4097 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4098 }
4099 }
Adam Powell326d8082009-12-09 15:10:07 -08004100 }
4101
4102 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004103 * Dispatch a hint about whether this view is displayed. For instance, when
4104 * a View moves out of the screen, it might receives a display hint indicating
4105 * the view is not displayed. Applications should not <em>rely</em> on this hint
4106 * as there is no guarantee that they will receive one.
4107 *
4108 * @param hint A hint about whether or not this view is displayed:
4109 * {@link #VISIBLE} or {@link #INVISIBLE}.
4110 */
4111 public void dispatchDisplayHint(int hint) {
4112 onDisplayHint(hint);
4113 }
4114
4115 /**
4116 * Gives this view a hint about whether is displayed or not. For instance, when
4117 * a View moves out of the screen, it might receives a display hint indicating
4118 * the view is not displayed. Applications should not <em>rely</em> on this hint
4119 * as there is no guarantee that they will receive one.
4120 *
4121 * @param hint A hint about whether or not this view is displayed:
4122 * {@link #VISIBLE} or {@link #INVISIBLE}.
4123 */
4124 protected void onDisplayHint(int hint) {
4125 }
4126
4127 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 * Dispatch a window visibility change down the view hierarchy.
4129 * ViewGroups should override to route to their children.
4130 *
4131 * @param visibility The new visibility of the window.
4132 *
4133 * @see #onWindowVisibilityChanged
4134 */
4135 public void dispatchWindowVisibilityChanged(int visibility) {
4136 onWindowVisibilityChanged(visibility);
4137 }
4138
4139 /**
4140 * Called when the window containing has change its visibility
4141 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4142 * that this tells you whether or not your window is being made visible
4143 * to the window manager; this does <em>not</em> tell you whether or not
4144 * your window is obscured by other windows on the screen, even if it
4145 * is itself visible.
4146 *
4147 * @param visibility The new visibility of the window.
4148 */
4149 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004150 if (visibility == VISIBLE) {
4151 initialAwakenScrollBars();
4152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 }
4154
4155 /**
4156 * Returns the current visibility of the window this view is attached to
4157 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4158 *
4159 * @return Returns the current visibility of the view's window.
4160 */
4161 public int getWindowVisibility() {
4162 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4163 }
4164
4165 /**
4166 * Retrieve the overall visible display size in which the window this view is
4167 * attached to has been positioned in. This takes into account screen
4168 * decorations above the window, for both cases where the window itself
4169 * is being position inside of them or the window is being placed under
4170 * then and covered insets are used for the window to position its content
4171 * inside. In effect, this tells you the available area where content can
4172 * be placed and remain visible to users.
4173 *
4174 * <p>This function requires an IPC back to the window manager to retrieve
4175 * the requested information, so should not be used in performance critical
4176 * code like drawing.
4177 *
4178 * @param outRect Filled in with the visible display frame. If the view
4179 * is not attached to a window, this is simply the raw display size.
4180 */
4181 public void getWindowVisibleDisplayFrame(Rect outRect) {
4182 if (mAttachInfo != null) {
4183 try {
4184 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4185 } catch (RemoteException e) {
4186 return;
4187 }
4188 // XXX This is really broken, and probably all needs to be done
4189 // in the window manager, and we need to know more about whether
4190 // we want the area behind or in front of the IME.
4191 final Rect insets = mAttachInfo.mVisibleInsets;
4192 outRect.left += insets.left;
4193 outRect.top += insets.top;
4194 outRect.right -= insets.right;
4195 outRect.bottom -= insets.bottom;
4196 return;
4197 }
4198 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4199 outRect.set(0, 0, d.getWidth(), d.getHeight());
4200 }
4201
4202 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004203 * Dispatch a notification about a resource configuration change down
4204 * the view hierarchy.
4205 * ViewGroups should override to route to their children.
4206 *
4207 * @param newConfig The new resource configuration.
4208 *
4209 * @see #onConfigurationChanged
4210 */
4211 public void dispatchConfigurationChanged(Configuration newConfig) {
4212 onConfigurationChanged(newConfig);
4213 }
4214
4215 /**
4216 * Called when the current configuration of the resources being used
4217 * by the application have changed. You can use this to decide when
4218 * to reload resources that can changed based on orientation and other
4219 * configuration characterstics. You only need to use this if you are
4220 * not relying on the normal {@link android.app.Activity} mechanism of
4221 * recreating the activity instance upon a configuration change.
4222 *
4223 * @param newConfig The new resource configuration.
4224 */
4225 protected void onConfigurationChanged(Configuration newConfig) {
4226 }
4227
4228 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229 * Private function to aggregate all per-view attributes in to the view
4230 * root.
4231 */
4232 void dispatchCollectViewAttributes(int visibility) {
4233 performCollectViewAttributes(visibility);
4234 }
4235
4236 void performCollectViewAttributes(int visibility) {
4237 //noinspection PointlessBitwiseExpression
4238 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4239 == (VISIBLE | KEEP_SCREEN_ON)) {
4240 mAttachInfo.mKeepScreenOn = true;
4241 }
4242 }
4243
4244 void needGlobalAttributesUpdate(boolean force) {
4245 AttachInfo ai = mAttachInfo;
4246 if (ai != null) {
4247 if (ai.mKeepScreenOn || force) {
4248 ai.mRecomputeGlobalAttributes = true;
4249 }
4250 }
4251 }
4252
4253 /**
4254 * Returns whether the device is currently in touch mode. Touch mode is entered
4255 * once the user begins interacting with the device by touch, and affects various
4256 * things like whether focus is always visible to the user.
4257 *
4258 * @return Whether the device is in touch mode.
4259 */
4260 @ViewDebug.ExportedProperty
4261 public boolean isInTouchMode() {
4262 if (mAttachInfo != null) {
4263 return mAttachInfo.mInTouchMode;
4264 } else {
4265 return ViewRoot.isInTouchMode();
4266 }
4267 }
4268
4269 /**
4270 * Returns the context the view is running in, through which it can
4271 * access the current theme, resources, etc.
4272 *
4273 * @return The view's Context.
4274 */
4275 @ViewDebug.CapturedViewProperty
4276 public final Context getContext() {
4277 return mContext;
4278 }
4279
4280 /**
4281 * Handle a key event before it is processed by any input method
4282 * associated with the view hierarchy. This can be used to intercept
4283 * key events in special situations before the IME consumes them; a
4284 * typical example would be handling the BACK key to update the application's
4285 * UI instead of allowing the IME to see it and close itself.
4286 *
4287 * @param keyCode The value in event.getKeyCode().
4288 * @param event Description of the key event.
4289 * @return If you handled the event, return true. If you want to allow the
4290 * event to be handled by the next receiver, return false.
4291 */
4292 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4293 return false;
4294 }
4295
4296 /**
4297 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4298 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
4299 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4300 * is released, if the view is enabled and clickable.
4301 *
4302 * @param keyCode A key code that represents the button pressed, from
4303 * {@link android.view.KeyEvent}.
4304 * @param event The KeyEvent object that defines the button action.
4305 */
4306 public boolean onKeyDown(int keyCode, KeyEvent event) {
4307 boolean result = false;
4308
4309 switch (keyCode) {
4310 case KeyEvent.KEYCODE_DPAD_CENTER:
4311 case KeyEvent.KEYCODE_ENTER: {
4312 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4313 return true;
4314 }
4315 // Long clickable items don't necessarily have to be clickable
4316 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4317 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4318 (event.getRepeatCount() == 0)) {
4319 setPressed(true);
4320 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004321 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 }
4323 return true;
4324 }
4325 break;
4326 }
4327 }
4328 return result;
4329 }
4330
4331 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004332 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4333 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4334 * the event).
4335 */
4336 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4337 return false;
4338 }
4339
4340 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004341 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4342 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
4343 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4344 * {@link KeyEvent#KEYCODE_ENTER} is released.
4345 *
4346 * @param keyCode A key code that represents the button pressed, from
4347 * {@link android.view.KeyEvent}.
4348 * @param event The KeyEvent object that defines the button action.
4349 */
4350 public boolean onKeyUp(int keyCode, KeyEvent event) {
4351 boolean result = false;
4352
4353 switch (keyCode) {
4354 case KeyEvent.KEYCODE_DPAD_CENTER:
4355 case KeyEvent.KEYCODE_ENTER: {
4356 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4357 return true;
4358 }
4359 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4360 setPressed(false);
4361
4362 if (!mHasPerformedLongPress) {
4363 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004364 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365
4366 result = performClick();
4367 }
4368 }
4369 break;
4370 }
4371 }
4372 return result;
4373 }
4374
4375 /**
4376 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4377 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4378 * the event).
4379 *
4380 * @param keyCode A key code that represents the button pressed, from
4381 * {@link android.view.KeyEvent}.
4382 * @param repeatCount The number of times the action was made.
4383 * @param event The KeyEvent object that defines the button action.
4384 */
4385 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4386 return false;
4387 }
4388
4389 /**
4390 * Called when an unhandled key shortcut event occurs.
4391 *
4392 * @param keyCode The value in event.getKeyCode().
4393 * @param event Description of the key event.
4394 * @return If you handled the event, return true. If you want to allow the
4395 * event to be handled by the next receiver, return false.
4396 */
4397 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4398 return false;
4399 }
4400
4401 /**
4402 * Check whether the called view is a text editor, in which case it
4403 * would make sense to automatically display a soft input window for
4404 * it. Subclasses should override this if they implement
4405 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004406 * a call on that method would return a non-null InputConnection, and
4407 * they are really a first-class editor that the user would normally
4408 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004409 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004410 * <p>The default implementation always returns false. This does
4411 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4412 * will not be called or the user can not otherwise perform edits on your
4413 * view; it is just a hint to the system that this is not the primary
4414 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004415 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004416 * @return Returns true if this view is a text editor, else false.
4417 */
4418 public boolean onCheckIsTextEditor() {
4419 return false;
4420 }
Romain Guy8506ab42009-06-11 17:35:47 -07004421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 /**
4423 * Create a new InputConnection for an InputMethod to interact
4424 * with the view. The default implementation returns null, since it doesn't
4425 * support input methods. You can override this to implement such support.
4426 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004427 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004428 * <p>When implementing this, you probably also want to implement
4429 * {@link #onCheckIsTextEditor()} to indicate you will return a
4430 * non-null InputConnection.
4431 *
4432 * @param outAttrs Fill in with attribute information about the connection.
4433 */
4434 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4435 return null;
4436 }
4437
4438 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004439 * Called by the {@link android.view.inputmethod.InputMethodManager}
4440 * when a view who is not the current
4441 * input connection target is trying to make a call on the manager. The
4442 * default implementation returns false; you can override this to return
4443 * true for certain views if you are performing InputConnection proxying
4444 * to them.
4445 * @param view The View that is making the InputMethodManager call.
4446 * @return Return true to allow the call, false to reject.
4447 */
4448 public boolean checkInputConnectionProxy(View view) {
4449 return false;
4450 }
Romain Guy8506ab42009-06-11 17:35:47 -07004451
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004452 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453 * Show the context menu for this view. It is not safe to hold on to the
4454 * menu after returning from this method.
4455 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004456 * You should normally not overload this method. Overload
4457 * {@link #onCreateContextMenu(ContextMenu)} or define an
4458 * {@link OnCreateContextMenuListener} to add items to the context menu.
4459 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004460 * @param menu The context menu to populate
4461 */
4462 public void createContextMenu(ContextMenu menu) {
4463 ContextMenuInfo menuInfo = getContextMenuInfo();
4464
4465 // Sets the current menu info so all items added to menu will have
4466 // my extra info set.
4467 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4468
4469 onCreateContextMenu(menu);
4470 if (mOnCreateContextMenuListener != null) {
4471 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4472 }
4473
4474 // Clear the extra information so subsequent items that aren't mine don't
4475 // have my extra info.
4476 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4477
4478 if (mParent != null) {
4479 mParent.createContextMenu(menu);
4480 }
4481 }
4482
4483 /**
4484 * Views should implement this if they have extra information to associate
4485 * with the context menu. The return result is supplied as a parameter to
4486 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4487 * callback.
4488 *
4489 * @return Extra information about the item for which the context menu
4490 * should be shown. This information will vary across different
4491 * subclasses of View.
4492 */
4493 protected ContextMenuInfo getContextMenuInfo() {
4494 return null;
4495 }
4496
4497 /**
4498 * Views should implement this if the view itself is going to add items to
4499 * the context menu.
4500 *
4501 * @param menu the context menu to populate
4502 */
4503 protected void onCreateContextMenu(ContextMenu menu) {
4504 }
4505
4506 /**
4507 * Implement this method to handle trackball motion events. The
4508 * <em>relative</em> movement of the trackball since the last event
4509 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4510 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4511 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4512 * they will often be fractional values, representing the more fine-grained
4513 * movement information available from a trackball).
4514 *
4515 * @param event The motion event.
4516 * @return True if the event was handled, false otherwise.
4517 */
4518 public boolean onTrackballEvent(MotionEvent event) {
4519 return false;
4520 }
4521
4522 /**
4523 * Implement this method to handle touch screen motion events.
4524 *
4525 * @param event The motion event.
4526 * @return True if the event was handled, false otherwise.
4527 */
4528 public boolean onTouchEvent(MotionEvent event) {
4529 final int viewFlags = mViewFlags;
4530
4531 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4532 // A disabled view that is clickable still consumes the touch
4533 // events, it just doesn't respond to them.
4534 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4535 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4536 }
4537
4538 if (mTouchDelegate != null) {
4539 if (mTouchDelegate.onTouchEvent(event)) {
4540 return true;
4541 }
4542 }
4543
4544 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4545 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4546 switch (event.getAction()) {
4547 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004548 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4549 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004550 // take focus if we don't have it already and we should in
4551 // touch mode.
4552 boolean focusTaken = false;
4553 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4554 focusTaken = requestFocus();
4555 }
4556
4557 if (!mHasPerformedLongPress) {
4558 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004559 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004560
4561 // Only perform take click actions if we were in the pressed state
4562 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08004563 // Use a Runnable and post this rather than calling
4564 // performClick directly. This lets other visual state
4565 // of the view update before click actions start.
4566 if (mPerformClick == null) {
4567 mPerformClick = new PerformClick();
4568 }
4569 if (!post(mPerformClick)) {
4570 performClick();
4571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572 }
4573 }
4574
4575 if (mUnsetPressedState == null) {
4576 mUnsetPressedState = new UnsetPressedState();
4577 }
4578
Adam Powelle14579b2009-12-16 18:39:52 -08004579 if (prepressed) {
4580 mPrivateFlags |= PRESSED;
4581 refreshDrawableState();
4582 postDelayed(mUnsetPressedState,
4583 ViewConfiguration.getPressedStateDuration());
4584 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004585 // If the post failed, unpress right now
4586 mUnsetPressedState.run();
4587 }
Adam Powelle14579b2009-12-16 18:39:52 -08004588 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004589 }
4590 break;
4591
4592 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004593 if (mPendingCheckForTap == null) {
4594 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 }
Adam Powelle14579b2009-12-16 18:39:52 -08004596 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004597 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004598 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 break;
4600
4601 case MotionEvent.ACTION_CANCEL:
4602 mPrivateFlags &= ~PRESSED;
4603 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004604 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 break;
4606
4607 case MotionEvent.ACTION_MOVE:
4608 final int x = (int) event.getX();
4609 final int y = (int) event.getY();
4610
4611 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07004612 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004614 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004615 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004616 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004617 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004618
4619 // Need to switch from pressed to not pressed
4620 mPrivateFlags &= ~PRESSED;
4621 refreshDrawableState();
4622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004623 }
4624 break;
4625 }
4626 return true;
4627 }
4628
4629 return false;
4630 }
4631
4632 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004633 * Remove the longpress detection timer.
4634 */
4635 private void removeLongPressCallback() {
4636 if (mPendingCheckForLongPress != null) {
4637 removeCallbacks(mPendingCheckForLongPress);
4638 }
4639 }
Adam Powelle14579b2009-12-16 18:39:52 -08004640
4641 /**
Romain Guya440b002010-02-24 15:57:54 -08004642 * Remove the prepress detection timer.
4643 */
4644 private void removeUnsetPressCallback() {
4645 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
4646 setPressed(false);
4647 removeCallbacks(mUnsetPressedState);
4648 }
4649 }
4650
4651 /**
Adam Powelle14579b2009-12-16 18:39:52 -08004652 * Remove the tap detection timer.
4653 */
4654 private void removeTapCallback() {
4655 if (mPendingCheckForTap != null) {
4656 mPrivateFlags &= ~PREPRESSED;
4657 removeCallbacks(mPendingCheckForTap);
4658 }
4659 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004660
4661 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004662 * Cancels a pending long press. Your subclass can use this if you
4663 * want the context menu to come up if the user presses and holds
4664 * at the same place, but you don't want it to come up if they press
4665 * and then move around enough to cause scrolling.
4666 */
4667 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004668 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004669
4670 /*
4671 * The prepressed state handled by the tap callback is a display
4672 * construct, but the tap callback will post a long press callback
4673 * less its own timeout. Remove it here.
4674 */
4675 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004676 }
4677
4678 /**
4679 * Sets the TouchDelegate for this View.
4680 */
4681 public void setTouchDelegate(TouchDelegate delegate) {
4682 mTouchDelegate = delegate;
4683 }
4684
4685 /**
4686 * Gets the TouchDelegate for this View.
4687 */
4688 public TouchDelegate getTouchDelegate() {
4689 return mTouchDelegate;
4690 }
4691
4692 /**
4693 * Set flags controlling behavior of this view.
4694 *
4695 * @param flags Constant indicating the value which should be set
4696 * @param mask Constant indicating the bit range that should be changed
4697 */
4698 void setFlags(int flags, int mask) {
4699 int old = mViewFlags;
4700 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4701
4702 int changed = mViewFlags ^ old;
4703 if (changed == 0) {
4704 return;
4705 }
4706 int privateFlags = mPrivateFlags;
4707
4708 /* Check if the FOCUSABLE bit has changed */
4709 if (((changed & FOCUSABLE_MASK) != 0) &&
4710 ((privateFlags & HAS_BOUNDS) !=0)) {
4711 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4712 && ((privateFlags & FOCUSED) != 0)) {
4713 /* Give up focus if we are no longer focusable */
4714 clearFocus();
4715 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4716 && ((privateFlags & FOCUSED) == 0)) {
4717 /*
4718 * Tell the view system that we are now available to take focus
4719 * if no one else already has it.
4720 */
4721 if (mParent != null) mParent.focusableViewAvailable(this);
4722 }
4723 }
4724
4725 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4726 if ((changed & VISIBILITY_MASK) != 0) {
4727 /*
4728 * If this view is becoming visible, set the DRAWN flag so that
4729 * the next invalidate() will not be skipped.
4730 */
4731 mPrivateFlags |= DRAWN;
4732
4733 needGlobalAttributesUpdate(true);
4734
4735 // a view becoming visible is worth notifying the parent
4736 // about in case nothing has focus. even if this specific view
4737 // isn't focusable, it may contain something that is, so let
4738 // the root view try to give this focus if nothing else does.
4739 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4740 mParent.focusableViewAvailable(this);
4741 }
4742 }
4743 }
4744
4745 /* Check if the GONE bit has changed */
4746 if ((changed & GONE) != 0) {
4747 needGlobalAttributesUpdate(false);
4748 requestLayout();
4749 invalidate();
4750
Romain Guyecd80ee2009-12-03 17:13:02 -08004751 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
4752 if (hasFocus()) clearFocus();
4753 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004754 }
4755 if (mAttachInfo != null) {
4756 mAttachInfo.mViewVisibilityChanged = true;
4757 }
4758 }
4759
4760 /* Check if the VISIBLE bit has changed */
4761 if ((changed & INVISIBLE) != 0) {
4762 needGlobalAttributesUpdate(false);
4763 invalidate();
4764
4765 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
4766 // root view becoming invisible shouldn't clear focus
4767 if (getRootView() != this) {
4768 clearFocus();
4769 }
4770 }
4771 if (mAttachInfo != null) {
4772 mAttachInfo.mViewVisibilityChanged = true;
4773 }
4774 }
4775
Adam Powell326d8082009-12-09 15:10:07 -08004776 if ((changed & VISIBILITY_MASK) != 0) {
4777 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
4778 }
4779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004780 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
4781 destroyDrawingCache();
4782 }
4783
4784 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
4785 destroyDrawingCache();
4786 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4787 }
4788
4789 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
4790 destroyDrawingCache();
4791 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4792 }
4793
4794 if ((changed & DRAW_MASK) != 0) {
4795 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
4796 if (mBGDrawable != null) {
4797 mPrivateFlags &= ~SKIP_DRAW;
4798 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
4799 } else {
4800 mPrivateFlags |= SKIP_DRAW;
4801 }
4802 } else {
4803 mPrivateFlags &= ~SKIP_DRAW;
4804 }
4805 requestLayout();
4806 invalidate();
4807 }
4808
4809 if ((changed & KEEP_SCREEN_ON) != 0) {
4810 if (mParent != null) {
4811 mParent.recomputeViewAttributes(this);
4812 }
4813 }
4814 }
4815
4816 /**
4817 * Change the view's z order in the tree, so it's on top of other sibling
4818 * views
4819 */
4820 public void bringToFront() {
4821 if (mParent != null) {
4822 mParent.bringChildToFront(this);
4823 }
4824 }
4825
4826 /**
4827 * This is called in response to an internal scroll in this view (i.e., the
4828 * view scrolled its own contents). This is typically as a result of
4829 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
4830 * called.
4831 *
4832 * @param l Current horizontal scroll origin.
4833 * @param t Current vertical scroll origin.
4834 * @param oldl Previous horizontal scroll origin.
4835 * @param oldt Previous vertical scroll origin.
4836 */
4837 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4838 mBackgroundSizeChanged = true;
4839
4840 final AttachInfo ai = mAttachInfo;
4841 if (ai != null) {
4842 ai.mViewScrollChanged = true;
4843 }
4844 }
4845
4846 /**
Chet Haase21cd1382010-09-01 17:42:29 -07004847 * Interface definition for a callback to be invoked when the layout bounds of a view
4848 * changes due to layout processing.
4849 */
4850 public interface OnLayoutChangeListener {
4851 /**
4852 * Called when the focus state of a view has changed.
4853 *
4854 * @param v The view whose state has changed.
4855 * @param left The new value of the view's left property.
4856 * @param top The new value of the view's top property.
4857 * @param right The new value of the view's right property.
4858 * @param bottom The new value of the view's bottom property.
4859 * @param oldLeft The previous value of the view's left property.
4860 * @param oldTop The previous value of the view's top property.
4861 * @param oldRight The previous value of the view's right property.
4862 * @param oldBottom The previous value of the view's bottom property.
4863 */
4864 void onLayoutChange(View v, int left, int top, int right, int bottom,
4865 int oldLeft, int oldTop, int oldRight, int oldBottom);
4866 }
4867
4868 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004869 * This is called during layout when the size of this view has changed. If
4870 * you were just added to the view hierarchy, you're called with the old
4871 * values of 0.
4872 *
4873 * @param w Current width of this view.
4874 * @param h Current height of this view.
4875 * @param oldw Old width of this view.
4876 * @param oldh Old height of this view.
4877 */
4878 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
4879 }
4880
4881 /**
4882 * Called by draw to draw the child views. This may be overridden
4883 * by derived classes to gain control just before its children are drawn
4884 * (but after its own view has been drawn).
4885 * @param canvas the canvas on which to draw the view
4886 */
4887 protected void dispatchDraw(Canvas canvas) {
4888 }
4889
4890 /**
4891 * Gets the parent of this view. Note that the parent is a
4892 * ViewParent and not necessarily a View.
4893 *
4894 * @return Parent of this view.
4895 */
4896 public final ViewParent getParent() {
4897 return mParent;
4898 }
4899
4900 /**
4901 * Return the scrolled left position of this view. This is the left edge of
4902 * the displayed part of your view. You do not need to draw any pixels
4903 * farther left, since those are outside of the frame of your view on
4904 * screen.
4905 *
4906 * @return The left edge of the displayed part of your view, in pixels.
4907 */
4908 public final int getScrollX() {
4909 return mScrollX;
4910 }
4911
4912 /**
4913 * Return the scrolled top position of this view. This is the top edge of
4914 * the displayed part of your view. You do not need to draw any pixels above
4915 * it, since those are outside of the frame of your view on screen.
4916 *
4917 * @return The top edge of the displayed part of your view, in pixels.
4918 */
4919 public final int getScrollY() {
4920 return mScrollY;
4921 }
4922
4923 /**
4924 * Return the width of the your view.
4925 *
4926 * @return The width of your view, in pixels.
4927 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004928 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004929 public final int getWidth() {
4930 return mRight - mLeft;
4931 }
4932
4933 /**
4934 * Return the height of your view.
4935 *
4936 * @return The height of your view, in pixels.
4937 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004938 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939 public final int getHeight() {
4940 return mBottom - mTop;
4941 }
4942
4943 /**
4944 * Return the visible drawing bounds of your view. Fills in the output
4945 * rectangle with the values from getScrollX(), getScrollY(),
4946 * getWidth(), and getHeight().
4947 *
4948 * @param outRect The (scrolled) drawing bounds of the view.
4949 */
4950 public void getDrawingRect(Rect outRect) {
4951 outRect.left = mScrollX;
4952 outRect.top = mScrollY;
4953 outRect.right = mScrollX + (mRight - mLeft);
4954 outRect.bottom = mScrollY + (mBottom - mTop);
4955 }
4956
4957 /**
4958 * The width of this view as measured in the most recent call to measure().
4959 * This should be used during measurement and layout calculations only. Use
4960 * {@link #getWidth()} to see how wide a view is after layout.
4961 *
4962 * @return The measured width of this view.
4963 */
4964 public final int getMeasuredWidth() {
4965 return mMeasuredWidth;
4966 }
4967
4968 /**
4969 * The height of this view as measured in the most recent call to measure().
4970 * This should be used during measurement and layout calculations only. Use
4971 * {@link #getHeight()} to see how tall a view is after layout.
4972 *
4973 * @return The measured height of this view.
4974 */
4975 public final int getMeasuredHeight() {
4976 return mMeasuredHeight;
4977 }
4978
4979 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07004980 * The transform matrix of this view, which is calculated based on the current
4981 * roation, scale, and pivot properties.
4982 *
4983 * @see #getRotation()
4984 * @see #getScaleX()
4985 * @see #getScaleY()
4986 * @see #getPivotX()
4987 * @see #getPivotY()
4988 * @return The current transform matrix for the view
4989 */
4990 public Matrix getMatrix() {
Romain Guy33e72ae2010-07-17 12:40:29 -07004991 hasIdentityMatrix();
4992 return mMatrix;
4993 }
4994
4995 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07004996 * Utility function to determine if the value is far enough away from zero to be
4997 * considered non-zero.
4998 * @param value A floating point value to check for zero-ness
4999 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5000 */
5001 private static boolean nonzero(float value) {
5002 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5003 }
5004
5005 /**
Romain Guy33e72ae2010-07-17 12:40:29 -07005006 * Recomputes the transform matrix if necessary.
5007 *
5008 * @return True if the transform matrix is the identity matrix, false otherwise.
5009 */
5010 boolean hasIdentityMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005011 if (mMatrixDirty) {
5012 // transform-related properties have changed since the last time someone
5013 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005014
5015 // Figure out if we need to update the pivot point
5016 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5017 if ((mRight - mLeft) != mPrevWidth && (mBottom - mTop) != mPrevHeight) {
5018 mPrevWidth = mRight - mLeft;
5019 mPrevHeight = mBottom - mTop;
5020 mPivotX = (float) mPrevWidth / 2f;
5021 mPivotY = (float) mPrevHeight / 2f;
5022 }
5023 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005024 mMatrix.reset();
Chet Haasedf030d22010-07-30 17:22:38 -07005025 mMatrix.setTranslate(mTranslationX, mTranslationY);
5026 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
Chet Haasec3aa3612010-06-17 08:50:37 -07005027 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005028 if (nonzero(mRotationX) || nonzero(mRotationY)) {
5029 if (mCamera == null) {
5030 mCamera = new Camera();
5031 matrix3D = new Matrix();
5032 }
5033 mCamera.save();
5034 mCamera.rotateX(mRotationX);
5035 mCamera.rotateY(mRotationY);
5036 mCamera.getMatrix(matrix3D);
5037 matrix3D.preTranslate(-mPivotX, -mPivotY);
5038 matrix3D.postTranslate(mPivotX, mPivotY);
5039 mMatrix.postConcat(matrix3D);
5040 mCamera.restore();
5041 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005042 mMatrixDirty = false;
5043 mMatrixIsIdentity = mMatrix.isIdentity();
5044 mInverseMatrixDirty = true;
5045 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005046 return mMatrixIsIdentity;
Chet Haasec3aa3612010-06-17 08:50:37 -07005047 }
5048
5049 /**
5050 * Utility method to retrieve the inverse of the current mMatrix property.
5051 * We cache the matrix to avoid recalculating it when transform properties
5052 * have not changed.
5053 *
5054 * @return The inverse of the current matrix of this view.
5055 */
5056 Matrix getInverseMatrix() {
5057 if (mInverseMatrixDirty) {
5058 if (mInverseMatrix == null) {
5059 mInverseMatrix = new Matrix();
5060 }
5061 mMatrix.invert(mInverseMatrix);
5062 mInverseMatrixDirty = false;
5063 }
5064 return mInverseMatrix;
5065 }
5066
5067 /**
5068 * The degrees that the view is rotated around the pivot point.
5069 *
5070 * @see #getPivotX()
5071 * @see #getPivotY()
5072 * @return The degrees of rotation.
5073 */
5074 public float getRotation() {
5075 return mRotation;
5076 }
5077
5078 /**
5079 * Sets the degrees that the view is rotated around the pivot point.
5080 *
5081 * @param rotation The degrees of rotation.
5082 * @see #getPivotX()
5083 * @see #getPivotY()
5084 */
5085 public void setRotation(float rotation) {
5086 if (mRotation != rotation) {
5087 // Double-invalidation is necessary to capture view's old and new areas
5088 invalidate();
5089 mRotation = rotation;
5090 mMatrixDirty = true;
5091 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5092 invalidate();
5093 }
5094 }
5095
5096 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005097 * The degrees that the view is rotated around the vertical axis through the pivot point.
5098 *
5099 * @see #getPivotX()
5100 * @see #getPivotY()
5101 * @return The degrees of Y rotation.
5102 */
5103 public float getRotationY() {
5104 return mRotationY;
5105 }
5106
5107 /**
5108 * Sets the degrees that the view is rotated around the vertical axis through pivot point.
5109 *
5110 * @param rotationY The degrees of Y rotation.
5111 * @see #getPivotX()
5112 * @see #getPivotY()
5113 */
5114 public void setRotationY(float rotationY) {
5115 if (mRotationY != rotationY) {
5116 // Double-invalidation is necessary to capture view's old and new areas
5117 invalidate();
5118 mRotationY = rotationY;
5119 mMatrixDirty = true;
5120 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5121 invalidate();
5122 }
5123 }
5124
5125 /**
5126 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5127 *
5128 * @see #getPivotX()
5129 * @see #getPivotY()
5130 * @return The degrees of X rotation.
5131 */
5132 public float getRotationX() {
5133 return mRotationX;
5134 }
5135
5136 /**
5137 * Sets the degrees that the view is rotated around the horizontal axis through pivot point.
5138 *
5139 * @param rotationX The degrees of X rotation.
5140 * @see #getPivotX()
5141 * @see #getPivotY()
5142 */
5143 public void setRotationX(float rotationX) {
5144 if (mRotationX != rotationX) {
5145 // Double-invalidation is necessary to capture view's old and new areas
5146 invalidate();
5147 mRotationX = rotationX;
5148 mMatrixDirty = true;
5149 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5150 invalidate();
5151 }
5152 }
5153
5154 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005155 * The amount that the view is scaled in x around the pivot point, as a proportion of
5156 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5157 *
5158 * @default 1.0f
5159 * @see #getPivotX()
5160 * @see #getPivotY()
5161 * @return The scaling factor.
5162 */
5163 public float getScaleX() {
5164 return mScaleX;
5165 }
5166
5167 /**
5168 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5169 * the view's unscaled width. A value of 1 means that no scaling is applied.
5170 *
5171 * @param scaleX The scaling factor.
5172 * @see #getPivotX()
5173 * @see #getPivotY()
5174 */
5175 public void setScaleX(float scaleX) {
5176 if (mScaleX != scaleX) {
5177 // Double-invalidation is necessary to capture view's old and new areas
5178 invalidate();
5179 mScaleX = scaleX;
5180 mMatrixDirty = true;
5181 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5182 invalidate();
5183 }
5184 }
5185
5186 /**
5187 * The amount that the view is scaled in y around the pivot point, as a proportion of
5188 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5189 *
5190 * @default 1.0f
5191 * @see #getPivotX()
5192 * @see #getPivotY()
5193 * @return The scaling factor.
5194 */
5195 public float getScaleY() {
5196 return mScaleY;
5197 }
5198
5199 /**
5200 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5201 * the view's unscaled width. A value of 1 means that no scaling is applied.
5202 *
5203 * @param scaleY The scaling factor.
5204 * @see #getPivotX()
5205 * @see #getPivotY()
5206 */
5207 public void setScaleY(float scaleY) {
5208 if (mScaleY != scaleY) {
5209 // Double-invalidation is necessary to capture view's old and new areas
5210 invalidate();
5211 mScaleY = scaleY;
5212 mMatrixDirty = true;
5213 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5214 invalidate();
5215 }
5216 }
5217
5218 /**
5219 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5220 * and {@link #setScaleX(float) scaled}.
5221 *
5222 * @see #getRotation()
5223 * @see #getScaleX()
5224 * @see #getScaleY()
5225 * @see #getPivotY()
5226 * @return The x location of the pivot point.
5227 */
5228 public float getPivotX() {
5229 return mPivotX;
5230 }
5231
5232 /**
5233 * Sets the x location of the point around which the view is
5234 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005235 * By default, the pivot point is centered on the object.
5236 * Setting this property disables this behavior and causes the view to use only the
5237 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005238 *
5239 * @param pivotX The x location of the pivot point.
5240 * @see #getRotation()
5241 * @see #getScaleX()
5242 * @see #getScaleY()
5243 * @see #getPivotY()
5244 */
5245 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005246 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005247 if (mPivotX != pivotX) {
5248 // Double-invalidation is necessary to capture view's old and new areas
5249 invalidate();
5250 mPivotX = pivotX;
5251 mMatrixDirty = true;
5252 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5253 invalidate();
5254 }
5255 }
5256
5257 /**
5258 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5259 * and {@link #setScaleY(float) scaled}.
5260 *
5261 * @see #getRotation()
5262 * @see #getScaleX()
5263 * @see #getScaleY()
5264 * @see #getPivotY()
5265 * @return The y location of the pivot point.
5266 */
5267 public float getPivotY() {
5268 return mPivotY;
5269 }
5270
5271 /**
5272 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005273 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5274 * Setting this property disables this behavior and causes the view to use only the
5275 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005276 *
5277 * @param pivotY The y location of the pivot point.
5278 * @see #getRotation()
5279 * @see #getScaleX()
5280 * @see #getScaleY()
5281 * @see #getPivotY()
5282 */
5283 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005284 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005285 if (mPivotY != pivotY) {
5286 // Double-invalidation is necessary to capture view's old and new areas
5287 invalidate();
5288 mPivotY = pivotY;
5289 mMatrixDirty = true;
5290 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5291 invalidate();
5292 }
5293 }
5294
5295 /**
5296 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5297 * completely transparent and 1 means the view is completely opaque.
5298 *
5299 * @default 1.0f
5300 * @return The opacity of the view.
5301 */
5302 public float getAlpha() {
5303 return mAlpha;
5304 }
5305
5306 /**
5307 * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5308 * completely transparent and 1 means the view is completely opaque.
5309 *
5310 * @param alpha The opacity of the view.
5311 */
5312 public void setAlpha(float alpha) {
5313 mAlpha = alpha;
Romain Guy9b34d452010-09-02 11:45:04 -07005314 onSetAlpha((int) (alpha * 255));
Chet Haasec3aa3612010-06-17 08:50:37 -07005315 invalidate();
5316 }
5317
5318 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005319 * Top position of this view relative to its parent.
5320 *
5321 * @return The top of this view, in pixels.
5322 */
5323 @ViewDebug.CapturedViewProperty
5324 public final int getTop() {
5325 return mTop;
5326 }
5327
5328 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005329 * Sets the top position of this view relative to its parent. This method is meant to be called
5330 * by the layout system and should not generally be called otherwise, because the property
5331 * may be changed at any time by the layout.
5332 *
5333 * @param top The top of this view, in pixels.
5334 */
5335 public final void setTop(int top) {
5336 if (top != mTop) {
5337 if (hasIdentityMatrix()) {
5338 final ViewParent p = mParent;
5339 if (p != null && mAttachInfo != null) {
5340 final Rect r = mAttachInfo.mTmpInvalRect;
5341 int minTop;
5342 int yLoc;
5343 if (top < mTop) {
5344 minTop = top;
5345 yLoc = top - mTop;
5346 } else {
5347 minTop = mTop;
5348 yLoc = 0;
5349 }
5350 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5351 p.invalidateChild(this, r);
5352 }
5353 } else {
5354 // Double-invalidation is necessary to capture view's old and new areas
5355 invalidate();
5356 }
5357
5358 mTop = top;
5359
5360 if (!mMatrixIsIdentity) {
5361 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5362 invalidate();
5363 }
5364 }
5365 }
5366
5367 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005368 * Bottom position of this view relative to its parent.
5369 *
5370 * @return The bottom of this view, in pixels.
5371 */
5372 @ViewDebug.CapturedViewProperty
5373 public final int getBottom() {
5374 return mBottom;
5375 }
5376
5377 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005378 * Sets the bottom position of this view relative to its parent. This method is meant to be
5379 * called by the layout system and should not generally be called otherwise, because the
5380 * property may be changed at any time by the layout.
5381 *
5382 * @param bottom The bottom of this view, in pixels.
5383 */
5384 public final void setBottom(int bottom) {
5385 if (bottom != mBottom) {
5386 if (hasIdentityMatrix()) {
5387 final ViewParent p = mParent;
5388 if (p != null && mAttachInfo != null) {
5389 final Rect r = mAttachInfo.mTmpInvalRect;
5390 int maxBottom;
5391 if (bottom < mBottom) {
5392 maxBottom = mBottom;
5393 } else {
5394 maxBottom = bottom;
5395 }
5396 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5397 p.invalidateChild(this, r);
5398 }
5399 } else {
5400 // Double-invalidation is necessary to capture view's old and new areas
5401 invalidate();
5402 }
5403
5404 mBottom = bottom;
5405
5406 if (!mMatrixIsIdentity) {
5407 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5408 invalidate();
5409 }
5410 }
5411 }
5412
5413 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005414 * Left position of this view relative to its parent.
5415 *
5416 * @return The left edge of this view, in pixels.
5417 */
5418 @ViewDebug.CapturedViewProperty
5419 public final int getLeft() {
5420 return mLeft;
5421 }
5422
5423 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005424 * Sets the left position of this view relative to its parent. This method is meant to be called
5425 * by the layout system and should not generally be called otherwise, because the property
5426 * may be changed at any time by the layout.
5427 *
5428 * @param left The bottom of this view, in pixels.
5429 */
5430 public final void setLeft(int left) {
5431 if (left != mLeft) {
5432 System.out.println("view " + this + " left = " + left);
5433 if (hasIdentityMatrix()) {
5434 final ViewParent p = mParent;
5435 if (p != null && mAttachInfo != null) {
5436 final Rect r = mAttachInfo.mTmpInvalRect;
5437 int minLeft;
5438 int xLoc;
5439 if (left < mLeft) {
5440 minLeft = left;
5441 xLoc = left - mLeft;
5442 } else {
5443 minLeft = mLeft;
5444 xLoc = 0;
5445 }
5446 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
5447 p.invalidateChild(this, r);
5448 }
5449 } else {
5450 // Double-invalidation is necessary to capture view's old and new areas
5451 invalidate();
5452 }
5453
5454 mLeft = left;
5455
5456 if (!mMatrixIsIdentity) {
5457 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5458 invalidate();
5459 }
5460 }
5461 }
5462
5463 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 * Right position of this view relative to its parent.
5465 *
5466 * @return The right edge of this view, in pixels.
5467 */
5468 @ViewDebug.CapturedViewProperty
5469 public final int getRight() {
5470 return mRight;
5471 }
5472
5473 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005474 * Sets the right position of this view relative to its parent. This method is meant to be called
5475 * by the layout system and should not generally be called otherwise, because the property
5476 * may be changed at any time by the layout.
5477 *
5478 * @param right The bottom of this view, in pixels.
5479 */
5480 public final void setRight(int right) {
5481 if (right != mRight) {
5482 if (hasIdentityMatrix()) {
5483 final ViewParent p = mParent;
5484 if (p != null && mAttachInfo != null) {
5485 final Rect r = mAttachInfo.mTmpInvalRect;
5486 int maxRight;
5487 if (right < mRight) {
5488 maxRight = mRight;
5489 } else {
5490 maxRight = right;
5491 }
5492 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
5493 p.invalidateChild(this, r);
5494 }
5495 } else {
5496 // Double-invalidation is necessary to capture view's old and new areas
5497 invalidate();
5498 }
5499
5500 mRight = right;
5501
5502 if (!mMatrixIsIdentity) {
5503 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5504 invalidate();
5505 }
5506 }
5507 }
5508
5509 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005510 * The visual x position of this view, in pixels. This is equivalent to the
5511 * {@link #setTranslationX(float) translationX} property plus the current
5512 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07005513 *
Chet Haasedf030d22010-07-30 17:22:38 -07005514 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005515 */
Chet Haasedf030d22010-07-30 17:22:38 -07005516 public float getX() {
5517 return mLeft + mTranslationX;
5518 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005519
Chet Haasedf030d22010-07-30 17:22:38 -07005520 /**
5521 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
5522 * {@link #setTranslationX(float) translationX} property to be the difference between
5523 * the x value passed in and the current {@link #getLeft() left} property.
5524 *
5525 * @param x The visual x position of this view, in pixels.
5526 */
5527 public void setX(float x) {
5528 setTranslationX(x - mLeft);
5529 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005530
Chet Haasedf030d22010-07-30 17:22:38 -07005531 /**
5532 * The visual y position of this view, in pixels. This is equivalent to the
5533 * {@link #setTranslationY(float) translationY} property plus the current
5534 * {@link #getTop() top} property.
5535 *
5536 * @return The visual y position of this view, in pixels.
5537 */
5538 public float getY() {
5539 return mTop + mTranslationY;
5540 }
5541
5542 /**
5543 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
5544 * {@link #setTranslationY(float) translationY} property to be the difference between
5545 * the y value passed in and the current {@link #getTop() top} property.
5546 *
5547 * @param y The visual y position of this view, in pixels.
5548 */
5549 public void setY(float y) {
5550 setTranslationY(y - mTop);
5551 }
5552
5553
5554 /**
5555 * The horizontal location of this view relative to its {@link #getLeft() left} position.
5556 * This position is post-layout, in addition to wherever the object's
5557 * layout placed it.
5558 *
5559 * @return The horizontal position of this view relative to its left position, in pixels.
5560 */
5561 public float getTranslationX() {
5562 return mTranslationX;
5563 }
5564
5565 /**
5566 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
5567 * This effectively positions the object post-layout, in addition to wherever the object's
5568 * layout placed it.
5569 *
5570 * @param translationX The horizontal position of this view relative to its left position,
5571 * in pixels.
5572 */
5573 public void setTranslationX(float translationX) {
5574 if (mTranslationX != translationX) {
5575 // Double-invalidation is necessary to capture view's old and new areas
5576 invalidate();
5577 mTranslationX = translationX;
5578 mMatrixDirty = true;
5579 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5580 invalidate();
Chet Haasec3aa3612010-06-17 08:50:37 -07005581 }
5582 }
5583
5584 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005585 * The horizontal location of this view relative to its {@link #getTop() top} position.
5586 * This position is post-layout, in addition to wherever the object's
5587 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005588 *
Chet Haasedf030d22010-07-30 17:22:38 -07005589 * @return The vertical position of this view relative to its top position,
5590 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005591 */
Chet Haasedf030d22010-07-30 17:22:38 -07005592 public float getTranslationY() {
5593 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07005594 }
5595
5596 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005597 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
5598 * This effectively positions the object post-layout, in addition to wherever the object's
5599 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005600 *
Chet Haasedf030d22010-07-30 17:22:38 -07005601 * @param translationY The vertical position of this view relative to its top position,
5602 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005603 */
Chet Haasedf030d22010-07-30 17:22:38 -07005604 public void setTranslationY(float translationY) {
5605 if (mTranslationY != translationY) {
5606 // Double-invalidation is necessary to capture view's old and new areas
5607 invalidate();
5608 mTranslationY = translationY;
5609 mMatrixDirty = true;
5610 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5611 invalidate();
5612 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005613 }
5614
5615 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 * Hit rectangle in parent's coordinates
5617 *
5618 * @param outRect The hit rectangle of the view.
5619 */
5620 public void getHitRect(Rect outRect) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005621 if (hasIdentityMatrix() || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005622 outRect.set(mLeft, mTop, mRight, mBottom);
5623 } else {
Adam Powellb5de9f32010-07-17 01:00:53 -07005624 Matrix m = getMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005625 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07005626 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Chet Haasec3aa3612010-06-17 08:50:37 -07005627 m.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07005628 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
5629 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07005630 }
5631 }
5632
5633 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005634 * Utility method to determine whether the given point, in local coordinates,
5635 * is inside the view, where the area of the view is expanded by the slop factor.
5636 * This method is called while processing touch-move events to determine if the event
5637 * is still within the view.
5638 */
5639 private boolean pointInView(float localX, float localY, float slop) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005640 return localX > -slop && localY > -slop && localX < ((mRight - mLeft) + slop) &&
5641 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 }
5643
5644 /**
5645 * When a view has focus and the user navigates away from it, the next view is searched for
5646 * starting from the rectangle filled in by this method.
5647 *
5648 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
5649 * view maintains some idea of internal selection, such as a cursor, or a selected row
5650 * or column, you should override this method and fill in a more specific rectangle.
5651 *
5652 * @param r The rectangle to fill in, in this view's coordinates.
5653 */
5654 public void getFocusedRect(Rect r) {
5655 getDrawingRect(r);
5656 }
5657
5658 /**
5659 * If some part of this view is not clipped by any of its parents, then
5660 * return that area in r in global (root) coordinates. To convert r to local
5661 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
5662 * -globalOffset.y)) If the view is completely clipped or translated out,
5663 * return false.
5664 *
5665 * @param r If true is returned, r holds the global coordinates of the
5666 * visible portion of this view.
5667 * @param globalOffset If true is returned, globalOffset holds the dx,dy
5668 * between this view and its root. globalOffet may be null.
5669 * @return true if r is non-empty (i.e. part of the view is visible at the
5670 * root level.
5671 */
5672 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
5673 int width = mRight - mLeft;
5674 int height = mBottom - mTop;
5675 if (width > 0 && height > 0) {
5676 r.set(0, 0, width, height);
5677 if (globalOffset != null) {
5678 globalOffset.set(-mScrollX, -mScrollY);
5679 }
5680 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
5681 }
5682 return false;
5683 }
5684
5685 public final boolean getGlobalVisibleRect(Rect r) {
5686 return getGlobalVisibleRect(r, null);
5687 }
5688
5689 public final boolean getLocalVisibleRect(Rect r) {
5690 Point offset = new Point();
5691 if (getGlobalVisibleRect(r, offset)) {
5692 r.offset(-offset.x, -offset.y); // make r local
5693 return true;
5694 }
5695 return false;
5696 }
5697
5698 /**
5699 * Offset this view's vertical location by the specified number of pixels.
5700 *
5701 * @param offset the number of pixels to offset the view by
5702 */
5703 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005704 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005705 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005706 final ViewParent p = mParent;
5707 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005708 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005709 int minTop;
5710 int maxBottom;
5711 int yLoc;
5712 if (offset < 0) {
5713 minTop = mTop + offset;
5714 maxBottom = mBottom;
5715 yLoc = offset;
5716 } else {
5717 minTop = mTop;
5718 maxBottom = mBottom + offset;
5719 yLoc = 0;
5720 }
5721 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
5722 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005723 }
5724 } else {
5725 invalidate();
5726 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005727
Chet Haasec3aa3612010-06-17 08:50:37 -07005728 mTop += offset;
5729 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005730
Chet Haasec3aa3612010-06-17 08:50:37 -07005731 if (!mMatrixIsIdentity) {
5732 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5733 invalidate();
5734 }
5735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 }
5737
5738 /**
5739 * Offset this view's horizontal location by the specified amount of pixels.
5740 *
5741 * @param offset the numer of pixels to offset the view by
5742 */
5743 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005744 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005745 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005746 final ViewParent p = mParent;
5747 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005748 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005749 int minLeft;
5750 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005751 if (offset < 0) {
5752 minLeft = mLeft + offset;
5753 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005754 } else {
5755 minLeft = mLeft;
5756 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005757 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005758 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07005759 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005760 }
5761 } else {
5762 invalidate();
5763 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005764
Chet Haasec3aa3612010-06-17 08:50:37 -07005765 mLeft += offset;
5766 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005767
Chet Haasec3aa3612010-06-17 08:50:37 -07005768 if (!mMatrixIsIdentity) {
5769 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5770 invalidate();
5771 }
5772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773 }
5774
5775 /**
5776 * Get the LayoutParams associated with this view. All views should have
5777 * layout parameters. These supply parameters to the <i>parent</i> of this
5778 * view specifying how it should be arranged. There are many subclasses of
5779 * ViewGroup.LayoutParams, and these correspond to the different subclasses
5780 * of ViewGroup that are responsible for arranging their children.
5781 * @return The LayoutParams associated with this view
5782 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07005783 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 public ViewGroup.LayoutParams getLayoutParams() {
5785 return mLayoutParams;
5786 }
5787
5788 /**
5789 * Set the layout parameters associated with this view. These supply
5790 * parameters to the <i>parent</i> of this view specifying how it should be
5791 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
5792 * correspond to the different subclasses of ViewGroup that are responsible
5793 * for arranging their children.
5794 *
5795 * @param params the layout parameters for this view
5796 */
5797 public void setLayoutParams(ViewGroup.LayoutParams params) {
5798 if (params == null) {
5799 throw new NullPointerException("params == null");
5800 }
5801 mLayoutParams = params;
5802 requestLayout();
5803 }
5804
5805 /**
5806 * Set the scrolled position of your view. This will cause a call to
5807 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5808 * invalidated.
5809 * @param x the x position to scroll to
5810 * @param y the y position to scroll to
5811 */
5812 public void scrollTo(int x, int y) {
5813 if (mScrollX != x || mScrollY != y) {
5814 int oldX = mScrollX;
5815 int oldY = mScrollY;
5816 mScrollX = x;
5817 mScrollY = y;
5818 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07005819 if (!awakenScrollBars()) {
5820 invalidate();
5821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 }
5823 }
5824
5825 /**
5826 * Move the scrolled position of your view. This will cause a call to
5827 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5828 * invalidated.
5829 * @param x the amount of pixels to scroll by horizontally
5830 * @param y the amount of pixels to scroll by vertically
5831 */
5832 public void scrollBy(int x, int y) {
5833 scrollTo(mScrollX + x, mScrollY + y);
5834 }
5835
5836 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07005837 * <p>Trigger the scrollbars to draw. When invoked this method starts an
5838 * animation to fade the scrollbars out after a default delay. If a subclass
5839 * provides animated scrolling, the start delay should equal the duration
5840 * of the scrolling animation.</p>
5841 *
5842 * <p>The animation starts only if at least one of the scrollbars is
5843 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
5844 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5845 * this method returns true, and false otherwise. If the animation is
5846 * started, this method calls {@link #invalidate()}; in that case the
5847 * caller should not call {@link #invalidate()}.</p>
5848 *
5849 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07005850 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07005851 *
5852 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
5853 * and {@link #scrollTo(int, int)}.</p>
5854 *
5855 * @return true if the animation is played, false otherwise
5856 *
5857 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07005858 * @see #scrollBy(int, int)
5859 * @see #scrollTo(int, int)
5860 * @see #isHorizontalScrollBarEnabled()
5861 * @see #isVerticalScrollBarEnabled()
5862 * @see #setHorizontalScrollBarEnabled(boolean)
5863 * @see #setVerticalScrollBarEnabled(boolean)
5864 */
5865 protected boolean awakenScrollBars() {
5866 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07005867 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07005868 }
5869
5870 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07005871 * Trigger the scrollbars to draw.
5872 * This method differs from awakenScrollBars() only in its default duration.
5873 * initialAwakenScrollBars() will show the scroll bars for longer than
5874 * usual to give the user more of a chance to notice them.
5875 *
5876 * @return true if the animation is played, false otherwise.
5877 */
5878 private boolean initialAwakenScrollBars() {
5879 return mScrollCache != null &&
5880 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
5881 }
5882
5883 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07005884 * <p>
5885 * Trigger the scrollbars to draw. When invoked this method starts an
5886 * animation to fade the scrollbars out after a fixed delay. If a subclass
5887 * provides animated scrolling, the start delay should equal the duration of
5888 * the scrolling animation.
5889 * </p>
5890 *
5891 * <p>
5892 * The animation starts only if at least one of the scrollbars is enabled,
5893 * as specified by {@link #isHorizontalScrollBarEnabled()} and
5894 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5895 * this method returns true, and false otherwise. If the animation is
5896 * started, this method calls {@link #invalidate()}; in that case the caller
5897 * should not call {@link #invalidate()}.
5898 * </p>
5899 *
5900 * <p>
5901 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07005902 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07005903 * </p>
5904 *
5905 * @param startDelay the delay, in milliseconds, after which the animation
5906 * should start; when the delay is 0, the animation starts
5907 * immediately
5908 * @return true if the animation is played, false otherwise
5909 *
Mike Cleronf116bf82009-09-27 19:14:12 -07005910 * @see #scrollBy(int, int)
5911 * @see #scrollTo(int, int)
5912 * @see #isHorizontalScrollBarEnabled()
5913 * @see #isVerticalScrollBarEnabled()
5914 * @see #setHorizontalScrollBarEnabled(boolean)
5915 * @see #setVerticalScrollBarEnabled(boolean)
5916 */
5917 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07005918 return awakenScrollBars(startDelay, true);
5919 }
5920
5921 /**
5922 * <p>
5923 * Trigger the scrollbars to draw. When invoked this method starts an
5924 * animation to fade the scrollbars out after a fixed delay. If a subclass
5925 * provides animated scrolling, the start delay should equal the duration of
5926 * the scrolling animation.
5927 * </p>
5928 *
5929 * <p>
5930 * The animation starts only if at least one of the scrollbars is enabled,
5931 * as specified by {@link #isHorizontalScrollBarEnabled()} and
5932 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5933 * this method returns true, and false otherwise. If the animation is
5934 * started, this method calls {@link #invalidate()} if the invalidate parameter
5935 * is set to true; in that case the caller
5936 * should not call {@link #invalidate()}.
5937 * </p>
5938 *
5939 * <p>
5940 * This method should be invoked everytime a subclass directly updates the
5941 * scroll parameters.
5942 * </p>
5943 *
5944 * @param startDelay the delay, in milliseconds, after which the animation
5945 * should start; when the delay is 0, the animation starts
5946 * immediately
5947 *
5948 * @param invalidate Wheter this method should call invalidate
5949 *
5950 * @return true if the animation is played, false otherwise
5951 *
5952 * @see #scrollBy(int, int)
5953 * @see #scrollTo(int, int)
5954 * @see #isHorizontalScrollBarEnabled()
5955 * @see #isVerticalScrollBarEnabled()
5956 * @see #setHorizontalScrollBarEnabled(boolean)
5957 * @see #setVerticalScrollBarEnabled(boolean)
5958 */
5959 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07005960 final ScrollabilityCache scrollCache = mScrollCache;
5961
5962 if (scrollCache == null || !scrollCache.fadeScrollBars) {
5963 return false;
5964 }
5965
5966 if (scrollCache.scrollBar == null) {
5967 scrollCache.scrollBar = new ScrollBarDrawable();
5968 }
5969
5970 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
5971
Mike Cleron290947b2009-09-29 18:34:32 -07005972 if (invalidate) {
5973 // Invalidate to show the scrollbars
5974 invalidate();
5975 }
Mike Cleronf116bf82009-09-27 19:14:12 -07005976
5977 if (scrollCache.state == ScrollabilityCache.OFF) {
5978 // FIXME: this is copied from WindowManagerService.
5979 // We should get this value from the system when it
5980 // is possible to do so.
5981 final int KEY_REPEAT_FIRST_DELAY = 750;
5982 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
5983 }
5984
5985 // Tell mScrollCache when we should start fading. This may
5986 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07005987 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07005988 scrollCache.fadeStartTime = fadeStartTime;
5989 scrollCache.state = ScrollabilityCache.ON;
5990
5991 // Schedule our fader to run, unscheduling any old ones first
5992 if (mAttachInfo != null) {
5993 mAttachInfo.mHandler.removeCallbacks(scrollCache);
5994 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
5995 }
5996
5997 return true;
5998 }
5999
6000 return false;
6001 }
6002
6003 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 * Mark the the area defined by dirty as needing to be drawn. If the view is
6005 * visible, {@link #onDraw} will be called at some point in the future.
6006 * This must be called from a UI thread. To call from a non-UI thread, call
6007 * {@link #postInvalidate()}.
6008 *
6009 * WARNING: This method is destructive to dirty.
6010 * @param dirty the rectangle representing the bounds of the dirty region
6011 */
6012 public void invalidate(Rect dirty) {
6013 if (ViewDebug.TRACE_HIERARCHY) {
6014 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6015 }
6016
6017 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6018 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6019 final ViewParent p = mParent;
6020 final AttachInfo ai = mAttachInfo;
6021 if (p != null && ai != null) {
6022 final int scrollX = mScrollX;
6023 final int scrollY = mScrollY;
6024 final Rect r = ai.mTmpInvalRect;
6025 r.set(dirty.left - scrollX, dirty.top - scrollY,
6026 dirty.right - scrollX, dirty.bottom - scrollY);
6027 mParent.invalidateChild(this, r);
6028 }
6029 }
6030 }
6031
6032 /**
6033 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6034 * The coordinates of the dirty rect are relative to the view.
6035 * If the view is visible, {@link #onDraw} will be called at some point
6036 * in the future. This must be called from a UI thread. To call
6037 * from a non-UI thread, call {@link #postInvalidate()}.
6038 * @param l the left position of the dirty region
6039 * @param t the top position of the dirty region
6040 * @param r the right position of the dirty region
6041 * @param b the bottom position of the dirty region
6042 */
6043 public void invalidate(int l, int t, int r, int b) {
6044 if (ViewDebug.TRACE_HIERARCHY) {
6045 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6046 }
6047
6048 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6049 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6050 final ViewParent p = mParent;
6051 final AttachInfo ai = mAttachInfo;
6052 if (p != null && ai != null && l < r && t < b) {
6053 final int scrollX = mScrollX;
6054 final int scrollY = mScrollY;
6055 final Rect tmpr = ai.mTmpInvalRect;
6056 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6057 p.invalidateChild(this, tmpr);
6058 }
6059 }
6060 }
6061
6062 /**
6063 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6064 * be called at some point in the future. This must be called from a
6065 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6066 */
6067 public void invalidate() {
6068 if (ViewDebug.TRACE_HIERARCHY) {
6069 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6070 }
6071
6072 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6073 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
6074 final ViewParent p = mParent;
6075 final AttachInfo ai = mAttachInfo;
6076 if (p != null && ai != null) {
6077 final Rect r = ai.mTmpInvalRect;
6078 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6079 // Don't call invalidate -- we don't want to internally scroll
6080 // our own bounds
6081 p.invalidateChild(this, r);
6082 }
6083 }
6084 }
6085
6086 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006087 * Indicates whether this View is opaque. An opaque View guarantees that it will
6088 * draw all the pixels overlapping its bounds using a fully opaque color.
6089 *
6090 * Subclasses of View should override this method whenever possible to indicate
6091 * whether an instance is opaque. Opaque Views are treated in a special way by
6092 * the View hierarchy, possibly allowing it to perform optimizations during
6093 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006094 *
Romain Guy24443ea2009-05-11 11:56:30 -07006095 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006096 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006097 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006098 public boolean isOpaque() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006099 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK;
6100 }
6101
6102 private void computeOpaqueFlags() {
6103 // Opaque if:
6104 // - Has a background
6105 // - Background is opaque
6106 // - Doesn't have scrollbars or scrollbars are inside overlay
6107
6108 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6109 mPrivateFlags |= OPAQUE_BACKGROUND;
6110 } else {
6111 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6112 }
6113
6114 final int flags = mViewFlags;
6115 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6116 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6117 mPrivateFlags |= OPAQUE_SCROLLBARS;
6118 } else {
6119 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6120 }
6121 }
6122
6123 /**
6124 * @hide
6125 */
6126 protected boolean hasOpaqueScrollbars() {
6127 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006128 }
6129
6130 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 * @return A handler associated with the thread running the View. This
6132 * handler can be used to pump events in the UI events queue.
6133 */
6134 public Handler getHandler() {
6135 if (mAttachInfo != null) {
6136 return mAttachInfo.mHandler;
6137 }
6138 return null;
6139 }
6140
6141 /**
6142 * Causes the Runnable to be added to the message queue.
6143 * The runnable will be run on the user interface thread.
6144 *
6145 * @param action The Runnable that will be executed.
6146 *
6147 * @return Returns true if the Runnable was successfully placed in to the
6148 * message queue. Returns false on failure, usually because the
6149 * looper processing the message queue is exiting.
6150 */
6151 public boolean post(Runnable action) {
6152 Handler handler;
6153 if (mAttachInfo != null) {
6154 handler = mAttachInfo.mHandler;
6155 } else {
6156 // Assume that post will succeed later
6157 ViewRoot.getRunQueue().post(action);
6158 return true;
6159 }
6160
6161 return handler.post(action);
6162 }
6163
6164 /**
6165 * Causes the Runnable to be added to the message queue, to be run
6166 * after the specified amount of time elapses.
6167 * The runnable will be run on the user interface thread.
6168 *
6169 * @param action The Runnable that will be executed.
6170 * @param delayMillis The delay (in milliseconds) until the Runnable
6171 * will be executed.
6172 *
6173 * @return true if the Runnable was successfully placed in to the
6174 * message queue. Returns false on failure, usually because the
6175 * looper processing the message queue is exiting. Note that a
6176 * result of true does not mean the Runnable will be processed --
6177 * if the looper is quit before the delivery time of the message
6178 * occurs then the message will be dropped.
6179 */
6180 public boolean postDelayed(Runnable action, long delayMillis) {
6181 Handler handler;
6182 if (mAttachInfo != null) {
6183 handler = mAttachInfo.mHandler;
6184 } else {
6185 // Assume that post will succeed later
6186 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6187 return true;
6188 }
6189
6190 return handler.postDelayed(action, delayMillis);
6191 }
6192
6193 /**
6194 * Removes the specified Runnable from the message queue.
6195 *
6196 * @param action The Runnable to remove from the message handling queue
6197 *
6198 * @return true if this view could ask the Handler to remove the Runnable,
6199 * false otherwise. When the returned value is true, the Runnable
6200 * may or may not have been actually removed from the message queue
6201 * (for instance, if the Runnable was not in the queue already.)
6202 */
6203 public boolean removeCallbacks(Runnable action) {
6204 Handler handler;
6205 if (mAttachInfo != null) {
6206 handler = mAttachInfo.mHandler;
6207 } else {
6208 // Assume that post will succeed later
6209 ViewRoot.getRunQueue().removeCallbacks(action);
6210 return true;
6211 }
6212
6213 handler.removeCallbacks(action);
6214 return true;
6215 }
6216
6217 /**
6218 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6219 * Use this to invalidate the View from a non-UI thread.
6220 *
6221 * @see #invalidate()
6222 */
6223 public void postInvalidate() {
6224 postInvalidateDelayed(0);
6225 }
6226
6227 /**
6228 * Cause an invalidate of the specified area to happen on a subsequent cycle
6229 * through the event loop. Use this to invalidate the View from a non-UI thread.
6230 *
6231 * @param left The left coordinate of the rectangle to invalidate.
6232 * @param top The top coordinate of the rectangle to invalidate.
6233 * @param right The right coordinate of the rectangle to invalidate.
6234 * @param bottom The bottom coordinate of the rectangle to invalidate.
6235 *
6236 * @see #invalidate(int, int, int, int)
6237 * @see #invalidate(Rect)
6238 */
6239 public void postInvalidate(int left, int top, int right, int bottom) {
6240 postInvalidateDelayed(0, left, top, right, bottom);
6241 }
6242
6243 /**
6244 * Cause an invalidate to happen on a subsequent cycle through the event
6245 * loop. Waits for the specified amount of time.
6246 *
6247 * @param delayMilliseconds the duration in milliseconds to delay the
6248 * invalidation by
6249 */
6250 public void postInvalidateDelayed(long delayMilliseconds) {
6251 // We try only with the AttachInfo because there's no point in invalidating
6252 // if we are not attached to our window
6253 if (mAttachInfo != null) {
6254 Message msg = Message.obtain();
6255 msg.what = AttachInfo.INVALIDATE_MSG;
6256 msg.obj = this;
6257 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6258 }
6259 }
6260
6261 /**
6262 * Cause an invalidate of the specified area to happen on a subsequent cycle
6263 * through the event loop. Waits for the specified amount of time.
6264 *
6265 * @param delayMilliseconds the duration in milliseconds to delay the
6266 * invalidation by
6267 * @param left The left coordinate of the rectangle to invalidate.
6268 * @param top The top coordinate of the rectangle to invalidate.
6269 * @param right The right coordinate of the rectangle to invalidate.
6270 * @param bottom The bottom coordinate of the rectangle to invalidate.
6271 */
6272 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6273 int right, int bottom) {
6274
6275 // We try only with the AttachInfo because there's no point in invalidating
6276 // if we are not attached to our window
6277 if (mAttachInfo != null) {
6278 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6279 info.target = this;
6280 info.left = left;
6281 info.top = top;
6282 info.right = right;
6283 info.bottom = bottom;
6284
6285 final Message msg = Message.obtain();
6286 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6287 msg.obj = info;
6288 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6289 }
6290 }
6291
6292 /**
6293 * Called by a parent to request that a child update its values for mScrollX
6294 * and mScrollY if necessary. This will typically be done if the child is
6295 * animating a scroll using a {@link android.widget.Scroller Scroller}
6296 * object.
6297 */
6298 public void computeScroll() {
6299 }
6300
6301 /**
6302 * <p>Indicate whether the horizontal edges are faded when the view is
6303 * scrolled horizontally.</p>
6304 *
6305 * @return true if the horizontal edges should are faded on scroll, false
6306 * otherwise
6307 *
6308 * @see #setHorizontalFadingEdgeEnabled(boolean)
6309 * @attr ref android.R.styleable#View_fadingEdge
6310 */
6311 public boolean isHorizontalFadingEdgeEnabled() {
6312 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6313 }
6314
6315 /**
6316 * <p>Define whether the horizontal edges should be faded when this view
6317 * is scrolled horizontally.</p>
6318 *
6319 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6320 * be faded when the view is scrolled
6321 * horizontally
6322 *
6323 * @see #isHorizontalFadingEdgeEnabled()
6324 * @attr ref android.R.styleable#View_fadingEdge
6325 */
6326 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6327 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6328 if (horizontalFadingEdgeEnabled) {
6329 initScrollCache();
6330 }
6331
6332 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6333 }
6334 }
6335
6336 /**
6337 * <p>Indicate whether the vertical edges are faded when the view is
6338 * scrolled horizontally.</p>
6339 *
6340 * @return true if the vertical edges should are faded on scroll, false
6341 * otherwise
6342 *
6343 * @see #setVerticalFadingEdgeEnabled(boolean)
6344 * @attr ref android.R.styleable#View_fadingEdge
6345 */
6346 public boolean isVerticalFadingEdgeEnabled() {
6347 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
6348 }
6349
6350 /**
6351 * <p>Define whether the vertical edges should be faded when this view
6352 * is scrolled vertically.</p>
6353 *
6354 * @param verticalFadingEdgeEnabled true if the vertical edges should
6355 * be faded when the view is scrolled
6356 * vertically
6357 *
6358 * @see #isVerticalFadingEdgeEnabled()
6359 * @attr ref android.R.styleable#View_fadingEdge
6360 */
6361 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
6362 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
6363 if (verticalFadingEdgeEnabled) {
6364 initScrollCache();
6365 }
6366
6367 mViewFlags ^= FADING_EDGE_VERTICAL;
6368 }
6369 }
6370
6371 /**
6372 * Returns the strength, or intensity, of the top faded edge. The strength is
6373 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6374 * returns 0.0 or 1.0 but no value in between.
6375 *
6376 * Subclasses should override this method to provide a smoother fade transition
6377 * when scrolling occurs.
6378 *
6379 * @return the intensity of the top fade as a float between 0.0f and 1.0f
6380 */
6381 protected float getTopFadingEdgeStrength() {
6382 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
6383 }
6384
6385 /**
6386 * Returns the strength, or intensity, of the bottom faded edge. The strength is
6387 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6388 * returns 0.0 or 1.0 but no value in between.
6389 *
6390 * Subclasses should override this method to provide a smoother fade transition
6391 * when scrolling occurs.
6392 *
6393 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
6394 */
6395 protected float getBottomFadingEdgeStrength() {
6396 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
6397 computeVerticalScrollRange() ? 1.0f : 0.0f;
6398 }
6399
6400 /**
6401 * Returns the strength, or intensity, of the left faded edge. The strength is
6402 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6403 * returns 0.0 or 1.0 but no value in between.
6404 *
6405 * Subclasses should override this method to provide a smoother fade transition
6406 * when scrolling occurs.
6407 *
6408 * @return the intensity of the left fade as a float between 0.0f and 1.0f
6409 */
6410 protected float getLeftFadingEdgeStrength() {
6411 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
6412 }
6413
6414 /**
6415 * Returns the strength, or intensity, of the right faded edge. The strength is
6416 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6417 * returns 0.0 or 1.0 but no value in between.
6418 *
6419 * Subclasses should override this method to provide a smoother fade transition
6420 * when scrolling occurs.
6421 *
6422 * @return the intensity of the right fade as a float between 0.0f and 1.0f
6423 */
6424 protected float getRightFadingEdgeStrength() {
6425 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
6426 computeHorizontalScrollRange() ? 1.0f : 0.0f;
6427 }
6428
6429 /**
6430 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
6431 * scrollbar is not drawn by default.</p>
6432 *
6433 * @return true if the horizontal scrollbar should be painted, false
6434 * otherwise
6435 *
6436 * @see #setHorizontalScrollBarEnabled(boolean)
6437 */
6438 public boolean isHorizontalScrollBarEnabled() {
6439 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6440 }
6441
6442 /**
6443 * <p>Define whether the horizontal scrollbar should be drawn or not. The
6444 * scrollbar is not drawn by default.</p>
6445 *
6446 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
6447 * be painted
6448 *
6449 * @see #isHorizontalScrollBarEnabled()
6450 */
6451 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
6452 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
6453 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006454 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 recomputePadding();
6456 }
6457 }
6458
6459 /**
6460 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
6461 * scrollbar is not drawn by default.</p>
6462 *
6463 * @return true if the vertical scrollbar should be painted, false
6464 * otherwise
6465 *
6466 * @see #setVerticalScrollBarEnabled(boolean)
6467 */
6468 public boolean isVerticalScrollBarEnabled() {
6469 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
6470 }
6471
6472 /**
6473 * <p>Define whether the vertical scrollbar should be drawn or not. The
6474 * scrollbar is not drawn by default.</p>
6475 *
6476 * @param verticalScrollBarEnabled true if the vertical scrollbar should
6477 * be painted
6478 *
6479 * @see #isVerticalScrollBarEnabled()
6480 */
6481 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
6482 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
6483 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006484 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 recomputePadding();
6486 }
6487 }
6488
6489 private void recomputePadding() {
6490 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
6491 }
Mike Cleronfe81d382009-09-28 14:22:16 -07006492
6493 /**
6494 * Define whether scrollbars will fade when the view is not scrolling.
6495 *
6496 * @param fadeScrollbars wheter to enable fading
6497 *
6498 */
6499 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
6500 initScrollCache();
6501 final ScrollabilityCache scrollabilityCache = mScrollCache;
6502 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07006503 if (fadeScrollbars) {
6504 scrollabilityCache.state = ScrollabilityCache.OFF;
6505 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07006506 scrollabilityCache.state = ScrollabilityCache.ON;
6507 }
6508 }
6509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006510 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07006511 *
6512 * Returns true if scrollbars will fade when this view is not scrolling
6513 *
6514 * @return true if scrollbar fading is enabled
6515 */
6516 public boolean isScrollbarFadingEnabled() {
6517 return mScrollCache != null && mScrollCache.fadeScrollBars;
6518 }
6519
6520 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
6522 * inset. When inset, they add to the padding of the view. And the scrollbars
6523 * can be drawn inside the padding area or on the edge of the view. For example,
6524 * if a view has a background drawable and you want to draw the scrollbars
6525 * inside the padding specified by the drawable, you can use
6526 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
6527 * appear at the edge of the view, ignoring the padding, then you can use
6528 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
6529 * @param style the style of the scrollbars. Should be one of
6530 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
6531 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
6532 * @see #SCROLLBARS_INSIDE_OVERLAY
6533 * @see #SCROLLBARS_INSIDE_INSET
6534 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6535 * @see #SCROLLBARS_OUTSIDE_INSET
6536 */
6537 public void setScrollBarStyle(int style) {
6538 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
6539 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07006540 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 recomputePadding();
6542 }
6543 }
6544
6545 /**
6546 * <p>Returns the current scrollbar style.</p>
6547 * @return the current scrollbar style
6548 * @see #SCROLLBARS_INSIDE_OVERLAY
6549 * @see #SCROLLBARS_INSIDE_INSET
6550 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6551 * @see #SCROLLBARS_OUTSIDE_INSET
6552 */
6553 public int getScrollBarStyle() {
6554 return mViewFlags & SCROLLBARS_STYLE_MASK;
6555 }
6556
6557 /**
6558 * <p>Compute the horizontal range that the horizontal scrollbar
6559 * represents.</p>
6560 *
6561 * <p>The range is expressed in arbitrary units that must be the same as the
6562 * units used by {@link #computeHorizontalScrollExtent()} and
6563 * {@link #computeHorizontalScrollOffset()}.</p>
6564 *
6565 * <p>The default range is the drawing width of this view.</p>
6566 *
6567 * @return the total horizontal range represented by the horizontal
6568 * scrollbar
6569 *
6570 * @see #computeHorizontalScrollExtent()
6571 * @see #computeHorizontalScrollOffset()
6572 * @see android.widget.ScrollBarDrawable
6573 */
6574 protected int computeHorizontalScrollRange() {
6575 return getWidth();
6576 }
6577
6578 /**
6579 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
6580 * within the horizontal range. This value is used to compute the position
6581 * of the thumb within the scrollbar's track.</p>
6582 *
6583 * <p>The range is expressed in arbitrary units that must be the same as the
6584 * units used by {@link #computeHorizontalScrollRange()} and
6585 * {@link #computeHorizontalScrollExtent()}.</p>
6586 *
6587 * <p>The default offset is the scroll offset of this view.</p>
6588 *
6589 * @return the horizontal offset of the scrollbar's thumb
6590 *
6591 * @see #computeHorizontalScrollRange()
6592 * @see #computeHorizontalScrollExtent()
6593 * @see android.widget.ScrollBarDrawable
6594 */
6595 protected int computeHorizontalScrollOffset() {
6596 return mScrollX;
6597 }
6598
6599 /**
6600 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
6601 * within the horizontal range. This value is used to compute the length
6602 * of the thumb within the scrollbar's track.</p>
6603 *
6604 * <p>The range is expressed in arbitrary units that must be the same as the
6605 * units used by {@link #computeHorizontalScrollRange()} and
6606 * {@link #computeHorizontalScrollOffset()}.</p>
6607 *
6608 * <p>The default extent is the drawing width of this view.</p>
6609 *
6610 * @return the horizontal extent of the scrollbar's thumb
6611 *
6612 * @see #computeHorizontalScrollRange()
6613 * @see #computeHorizontalScrollOffset()
6614 * @see android.widget.ScrollBarDrawable
6615 */
6616 protected int computeHorizontalScrollExtent() {
6617 return getWidth();
6618 }
6619
6620 /**
6621 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
6622 *
6623 * <p>The range is expressed in arbitrary units that must be the same as the
6624 * units used by {@link #computeVerticalScrollExtent()} and
6625 * {@link #computeVerticalScrollOffset()}.</p>
6626 *
6627 * @return the total vertical range represented by the vertical scrollbar
6628 *
6629 * <p>The default range is the drawing height of this view.</p>
6630 *
6631 * @see #computeVerticalScrollExtent()
6632 * @see #computeVerticalScrollOffset()
6633 * @see android.widget.ScrollBarDrawable
6634 */
6635 protected int computeVerticalScrollRange() {
6636 return getHeight();
6637 }
6638
6639 /**
6640 * <p>Compute the vertical offset of the vertical scrollbar's thumb
6641 * within the horizontal range. This value is used to compute the position
6642 * of the thumb within the scrollbar's track.</p>
6643 *
6644 * <p>The range is expressed in arbitrary units that must be the same as the
6645 * units used by {@link #computeVerticalScrollRange()} and
6646 * {@link #computeVerticalScrollExtent()}.</p>
6647 *
6648 * <p>The default offset is the scroll offset of this view.</p>
6649 *
6650 * @return the vertical offset of the scrollbar's thumb
6651 *
6652 * @see #computeVerticalScrollRange()
6653 * @see #computeVerticalScrollExtent()
6654 * @see android.widget.ScrollBarDrawable
6655 */
6656 protected int computeVerticalScrollOffset() {
6657 return mScrollY;
6658 }
6659
6660 /**
6661 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
6662 * within the vertical range. This value is used to compute the length
6663 * of the thumb within the scrollbar's track.</p>
6664 *
6665 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08006666 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 * {@link #computeVerticalScrollOffset()}.</p>
6668 *
6669 * <p>The default extent is the drawing height of this view.</p>
6670 *
6671 * @return the vertical extent of the scrollbar's thumb
6672 *
6673 * @see #computeVerticalScrollRange()
6674 * @see #computeVerticalScrollOffset()
6675 * @see android.widget.ScrollBarDrawable
6676 */
6677 protected int computeVerticalScrollExtent() {
6678 return getHeight();
6679 }
6680
6681 /**
6682 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
6683 * scrollbars are painted only if they have been awakened first.</p>
6684 *
6685 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07006686 *
6687 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006688 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08006689 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 // scrollbars are drawn only when the animation is running
6691 final ScrollabilityCache cache = mScrollCache;
6692 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006693
6694 int state = cache.state;
6695
6696 if (state == ScrollabilityCache.OFF) {
6697 return;
6698 }
6699
6700 boolean invalidate = false;
6701
6702 if (state == ScrollabilityCache.FADING) {
6703 // We're fading -- get our fade interpolation
6704 if (cache.interpolatorValues == null) {
6705 cache.interpolatorValues = new float[1];
6706 }
6707
6708 float[] values = cache.interpolatorValues;
6709
6710 // Stops the animation if we're done
6711 if (cache.scrollBarInterpolator.timeToValues(values) ==
6712 Interpolator.Result.FREEZE_END) {
6713 cache.state = ScrollabilityCache.OFF;
6714 } else {
6715 cache.scrollBar.setAlpha(Math.round(values[0]));
6716 }
6717
6718 // This will make the scroll bars inval themselves after
6719 // drawing. We only want this when we're fading so that
6720 // we prevent excessive redraws
6721 invalidate = true;
6722 } else {
6723 // We're just on -- but we may have been fading before so
6724 // reset alpha
6725 cache.scrollBar.setAlpha(255);
6726 }
6727
6728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 final int viewFlags = mViewFlags;
6730
6731 final boolean drawHorizontalScrollBar =
6732 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6733 final boolean drawVerticalScrollBar =
6734 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
6735 && !isVerticalScrollBarHidden();
6736
6737 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
6738 final int width = mRight - mLeft;
6739 final int height = mBottom - mTop;
6740
6741 final ScrollBarDrawable scrollBar = cache.scrollBar;
6742 int size = scrollBar.getSize(false);
6743 if (size <= 0) {
6744 size = cache.scrollBarSize;
6745 }
6746
Mike Reede8853fc2009-09-04 14:01:48 -04006747 final int scrollX = mScrollX;
6748 final int scrollY = mScrollY;
6749 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
6750
Mike Cleronf116bf82009-09-27 19:14:12 -07006751 int left, top, right, bottom;
6752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006753 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006754 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04006755 computeHorizontalScrollOffset(),
6756 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04006757 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07006758 getVerticalScrollbarWidth() : 0;
6759 top = scrollY + height - size - (mUserPaddingBottom & inside);
6760 left = scrollX + (mPaddingLeft & inside);
6761 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
6762 bottom = top + size;
6763 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
6764 if (invalidate) {
6765 invalidate(left, top, right, bottom);
6766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 }
6768
6769 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04006770 scrollBar.setParameters(computeVerticalScrollRange(),
6771 computeVerticalScrollOffset(),
6772 computeVerticalScrollExtent(), true);
6773 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07006774 left = scrollX + width - size - (mUserPaddingRight & inside);
6775 top = scrollY + (mPaddingTop & inside);
6776 right = left + size;
6777 bottom = scrollY + height - (mUserPaddingBottom & inside);
6778 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
6779 if (invalidate) {
6780 invalidate(left, top, right, bottom);
6781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006782 }
6783 }
6784 }
6785 }
Romain Guy8506ab42009-06-11 17:35:47 -07006786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 /**
Romain Guy8506ab42009-06-11 17:35:47 -07006788 * 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 -08006789 * FastScroller is visible.
6790 * @return whether to temporarily hide the vertical scrollbar
6791 * @hide
6792 */
6793 protected boolean isVerticalScrollBarHidden() {
6794 return false;
6795 }
6796
6797 /**
6798 * <p>Draw the horizontal scrollbar if
6799 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
6800 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 * @param canvas the canvas on which to draw the scrollbar
6802 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006803 *
6804 * @see #isHorizontalScrollBarEnabled()
6805 * @see #computeHorizontalScrollRange()
6806 * @see #computeHorizontalScrollExtent()
6807 * @see #computeHorizontalScrollOffset()
6808 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07006809 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006810 */
Romain Guy8fb95422010-08-17 18:38:51 -07006811 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
6812 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006813 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006814 scrollBar.draw(canvas);
6815 }
Mike Reede8853fc2009-09-04 14:01:48 -04006816
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006817 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
6819 * returns true.</p>
6820 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006821 * @param canvas the canvas on which to draw the scrollbar
6822 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006823 *
6824 * @see #isVerticalScrollBarEnabled()
6825 * @see #computeVerticalScrollRange()
6826 * @see #computeVerticalScrollExtent()
6827 * @see #computeVerticalScrollOffset()
6828 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04006829 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006830 */
Romain Guy8fb95422010-08-17 18:38:51 -07006831 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
6832 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04006833 scrollBar.setBounds(l, t, r, b);
6834 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006835 }
6836
6837 /**
6838 * Implement this to do your drawing.
6839 *
6840 * @param canvas the canvas on which the background will be drawn
6841 */
6842 protected void onDraw(Canvas canvas) {
6843 }
6844
6845 /*
6846 * Caller is responsible for calling requestLayout if necessary.
6847 * (This allows addViewInLayout to not request a new layout.)
6848 */
6849 void assignParent(ViewParent parent) {
6850 if (mParent == null) {
6851 mParent = parent;
6852 } else if (parent == null) {
6853 mParent = null;
6854 } else {
6855 throw new RuntimeException("view " + this + " being added, but"
6856 + " it already has a parent");
6857 }
6858 }
6859
6860 /**
6861 * This is called when the view is attached to a window. At this point it
6862 * has a Surface and will start drawing. Note that this function is
6863 * guaranteed to be called before {@link #onDraw}, however it may be called
6864 * any time before the first onDraw -- including before or after
6865 * {@link #onMeasure}.
6866 *
6867 * @see #onDetachedFromWindow()
6868 */
6869 protected void onAttachedToWindow() {
6870 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
6871 mParent.requestTransparentRegion(this);
6872 }
Adam Powell8568c3a2010-04-19 14:26:11 -07006873 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
6874 initialAwakenScrollBars();
6875 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
6876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006877 }
6878
6879 /**
6880 * This is called when the view is detached from a window. At this point it
6881 * no longer has a surface for drawing.
6882 *
6883 * @see #onAttachedToWindow()
6884 */
6885 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08006886 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08006887 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05006888 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006889 destroyDrawingCache();
6890 }
6891
6892 /**
6893 * @return The number of times this view has been attached to a window
6894 */
6895 protected int getWindowAttachCount() {
6896 return mWindowAttachCount;
6897 }
6898
6899 /**
6900 * Retrieve a unique token identifying the window this view is attached to.
6901 * @return Return the window's token for use in
6902 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
6903 */
6904 public IBinder getWindowToken() {
6905 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
6906 }
6907
6908 /**
6909 * Retrieve a unique token identifying the top-level "real" window of
6910 * the window that this view is attached to. That is, this is like
6911 * {@link #getWindowToken}, except if the window this view in is a panel
6912 * window (attached to another containing window), then the token of
6913 * the containing window is returned instead.
6914 *
6915 * @return Returns the associated window token, either
6916 * {@link #getWindowToken()} or the containing window's token.
6917 */
6918 public IBinder getApplicationWindowToken() {
6919 AttachInfo ai = mAttachInfo;
6920 if (ai != null) {
6921 IBinder appWindowToken = ai.mPanelParentWindowToken;
6922 if (appWindowToken == null) {
6923 appWindowToken = ai.mWindowToken;
6924 }
6925 return appWindowToken;
6926 }
6927 return null;
6928 }
6929
6930 /**
6931 * Retrieve private session object this view hierarchy is using to
6932 * communicate with the window manager.
6933 * @return the session object to communicate with the window manager
6934 */
6935 /*package*/ IWindowSession getWindowSession() {
6936 return mAttachInfo != null ? mAttachInfo.mSession : null;
6937 }
6938
6939 /**
6940 * @param info the {@link android.view.View.AttachInfo} to associated with
6941 * this view
6942 */
6943 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
6944 //System.out.println("Attached! " + this);
6945 mAttachInfo = info;
6946 mWindowAttachCount++;
6947 if (mFloatingTreeObserver != null) {
6948 info.mTreeObserver.merge(mFloatingTreeObserver);
6949 mFloatingTreeObserver = null;
6950 }
6951 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
6952 mAttachInfo.mScrollContainers.add(this);
6953 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
6954 }
6955 performCollectViewAttributes(visibility);
6956 onAttachedToWindow();
6957 int vis = info.mWindowVisibility;
6958 if (vis != GONE) {
6959 onWindowVisibilityChanged(vis);
6960 }
6961 }
6962
6963 void dispatchDetachedFromWindow() {
6964 //System.out.println("Detached! " + this);
6965 AttachInfo info = mAttachInfo;
6966 if (info != null) {
6967 int vis = info.mWindowVisibility;
6968 if (vis != GONE) {
6969 onWindowVisibilityChanged(GONE);
6970 }
6971 }
6972
6973 onDetachedFromWindow();
6974 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
6975 mAttachInfo.mScrollContainers.remove(this);
6976 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
6977 }
6978 mAttachInfo = null;
6979 }
6980
6981 /**
6982 * Store this view hierarchy's frozen state into the given container.
6983 *
6984 * @param container The SparseArray in which to save the view's state.
6985 *
6986 * @see #restoreHierarchyState
6987 * @see #dispatchSaveInstanceState
6988 * @see #onSaveInstanceState
6989 */
6990 public void saveHierarchyState(SparseArray<Parcelable> container) {
6991 dispatchSaveInstanceState(container);
6992 }
6993
6994 /**
6995 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
6996 * May be overridden to modify how freezing happens to a view's children; for example, some
6997 * views may want to not store state for their children.
6998 *
6999 * @param container The SparseArray in which to save the view's state.
7000 *
7001 * @see #dispatchRestoreInstanceState
7002 * @see #saveHierarchyState
7003 * @see #onSaveInstanceState
7004 */
7005 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7006 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7007 mPrivateFlags &= ~SAVE_STATE_CALLED;
7008 Parcelable state = onSaveInstanceState();
7009 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7010 throw new IllegalStateException(
7011 "Derived class did not call super.onSaveInstanceState()");
7012 }
7013 if (state != null) {
7014 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7015 // + ": " + state);
7016 container.put(mID, state);
7017 }
7018 }
7019 }
7020
7021 /**
7022 * Hook allowing a view to generate a representation of its internal state
7023 * that can later be used to create a new instance with that same state.
7024 * This state should only contain information that is not persistent or can
7025 * not be reconstructed later. For example, you will never store your
7026 * current position on screen because that will be computed again when a
7027 * new instance of the view is placed in its view hierarchy.
7028 * <p>
7029 * Some examples of things you may store here: the current cursor position
7030 * in a text view (but usually not the text itself since that is stored in a
7031 * content provider or other persistent storage), the currently selected
7032 * item in a list view.
7033 *
7034 * @return Returns a Parcelable object containing the view's current dynamic
7035 * state, or null if there is nothing interesting to save. The
7036 * default implementation returns null.
7037 * @see #onRestoreInstanceState
7038 * @see #saveHierarchyState
7039 * @see #dispatchSaveInstanceState
7040 * @see #setSaveEnabled(boolean)
7041 */
7042 protected Parcelable onSaveInstanceState() {
7043 mPrivateFlags |= SAVE_STATE_CALLED;
7044 return BaseSavedState.EMPTY_STATE;
7045 }
7046
7047 /**
7048 * Restore this view hierarchy's frozen state from the given container.
7049 *
7050 * @param container The SparseArray which holds previously frozen states.
7051 *
7052 * @see #saveHierarchyState
7053 * @see #dispatchRestoreInstanceState
7054 * @see #onRestoreInstanceState
7055 */
7056 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7057 dispatchRestoreInstanceState(container);
7058 }
7059
7060 /**
7061 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7062 * children. May be overridden to modify how restoreing happens to a view's children; for
7063 * example, some views may want to not store state for their children.
7064 *
7065 * @param container The SparseArray which holds previously saved state.
7066 *
7067 * @see #dispatchSaveInstanceState
7068 * @see #restoreHierarchyState
7069 * @see #onRestoreInstanceState
7070 */
7071 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7072 if (mID != NO_ID) {
7073 Parcelable state = container.get(mID);
7074 if (state != null) {
7075 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7076 // + ": " + state);
7077 mPrivateFlags &= ~SAVE_STATE_CALLED;
7078 onRestoreInstanceState(state);
7079 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7080 throw new IllegalStateException(
7081 "Derived class did not call super.onRestoreInstanceState()");
7082 }
7083 }
7084 }
7085 }
7086
7087 /**
7088 * Hook allowing a view to re-apply a representation of its internal state that had previously
7089 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7090 * null state.
7091 *
7092 * @param state The frozen state that had previously been returned by
7093 * {@link #onSaveInstanceState}.
7094 *
7095 * @see #onSaveInstanceState
7096 * @see #restoreHierarchyState
7097 * @see #dispatchRestoreInstanceState
7098 */
7099 protected void onRestoreInstanceState(Parcelable state) {
7100 mPrivateFlags |= SAVE_STATE_CALLED;
7101 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007102 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7103 + "received " + state.getClass().toString() + " instead. This usually happens "
7104 + "when two views of different type have the same id in the same hierarchy. "
7105 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7106 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007107 }
7108 }
7109
7110 /**
7111 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7112 *
7113 * @return the drawing start time in milliseconds
7114 */
7115 public long getDrawingTime() {
7116 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7117 }
7118
7119 /**
7120 * <p>Enables or disables the duplication of the parent's state into this view. When
7121 * duplication is enabled, this view gets its drawable state from its parent rather
7122 * than from its own internal properties.</p>
7123 *
7124 * <p>Note: in the current implementation, setting this property to true after the
7125 * view was added to a ViewGroup might have no effect at all. This property should
7126 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7127 *
7128 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7129 * property is enabled, an exception will be thrown.</p>
7130 *
7131 * @param enabled True to enable duplication of the parent's drawable state, false
7132 * to disable it.
7133 *
7134 * @see #getDrawableState()
7135 * @see #isDuplicateParentStateEnabled()
7136 */
7137 public void setDuplicateParentStateEnabled(boolean enabled) {
7138 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7139 }
7140
7141 /**
7142 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7143 *
7144 * @return True if this view's drawable state is duplicated from the parent,
7145 * false otherwise
7146 *
7147 * @see #getDrawableState()
7148 * @see #setDuplicateParentStateEnabled(boolean)
7149 */
7150 public boolean isDuplicateParentStateEnabled() {
7151 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7152 }
7153
7154 /**
7155 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
7156 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
7157 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
7158 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
7159 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
7160 * null.</p>
7161 *
7162 * @param enabled true to enable the drawing cache, false otherwise
7163 *
7164 * @see #isDrawingCacheEnabled()
7165 * @see #getDrawingCache()
7166 * @see #buildDrawingCache()
7167 */
7168 public void setDrawingCacheEnabled(boolean enabled) {
7169 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
7170 }
7171
7172 /**
7173 * <p>Indicates whether the drawing cache is enabled for this view.</p>
7174 *
7175 * @return true if the drawing cache is enabled
7176 *
7177 * @see #setDrawingCacheEnabled(boolean)
7178 * @see #getDrawingCache()
7179 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07007180 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007181 public boolean isDrawingCacheEnabled() {
7182 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
7183 }
7184
7185 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007186 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
7187 *
7188 * @return A non-scaled bitmap representing this view or null if cache is disabled.
7189 *
7190 * @see #getDrawingCache(boolean)
7191 */
7192 public Bitmap getDrawingCache() {
7193 return getDrawingCache(false);
7194 }
7195
7196 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
7198 * is null when caching is disabled. If caching is enabled and the cache is not ready,
7199 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
7200 * draw from the cache when the cache is enabled. To benefit from the cache, you must
7201 * request the drawing cache by calling this method and draw it on screen if the
7202 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007203 *
7204 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7205 * this method will create a bitmap of the same size as this view. Because this bitmap
7206 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7207 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7208 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7209 * size than the view. This implies that your application must be able to handle this
7210 * size.</p>
7211 *
7212 * @param autoScale Indicates whether the generated bitmap should be scaled based on
7213 * the current density of the screen when the application is in compatibility
7214 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007215 *
Romain Guyfbd8f692009-06-26 14:51:58 -07007216 * @return A bitmap representing this view or null if cache is disabled.
7217 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007218 * @see #setDrawingCacheEnabled(boolean)
7219 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07007220 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007221 * @see #destroyDrawingCache()
7222 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007223 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7225 return null;
7226 }
7227 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007228 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007229 }
Romain Guy02890fd2010-08-06 17:58:44 -07007230 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007231 }
7232
7233 /**
7234 * <p>Frees the resources used by the drawing cache. If you call
7235 * {@link #buildDrawingCache()} manually without calling
7236 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7237 * should cleanup the cache with this method afterwards.</p>
7238 *
7239 * @see #setDrawingCacheEnabled(boolean)
7240 * @see #buildDrawingCache()
7241 * @see #getDrawingCache()
7242 */
7243 public void destroyDrawingCache() {
7244 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007245 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007246 mDrawingCache = null;
7247 }
Romain Guyfbd8f692009-06-26 14:51:58 -07007248 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007249 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07007250 mUnscaledDrawingCache = null;
7251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007252 }
7253
7254 /**
7255 * Setting a solid background color for the drawing cache's bitmaps will improve
7256 * perfromance and memory usage. Note, though that this should only be used if this
7257 * view will always be drawn on top of a solid color.
7258 *
7259 * @param color The background color to use for the drawing cache's bitmap
7260 *
7261 * @see #setDrawingCacheEnabled(boolean)
7262 * @see #buildDrawingCache()
7263 * @see #getDrawingCache()
7264 */
7265 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08007266 if (color != mDrawingCacheBackgroundColor) {
7267 mDrawingCacheBackgroundColor = color;
7268 mPrivateFlags &= ~DRAWING_CACHE_VALID;
7269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007270 }
7271
7272 /**
7273 * @see #setDrawingCacheBackgroundColor(int)
7274 *
7275 * @return The background color to used for the drawing cache's bitmap
7276 */
7277 public int getDrawingCacheBackgroundColor() {
7278 return mDrawingCacheBackgroundColor;
7279 }
7280
7281 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007282 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
7283 *
7284 * @see #buildDrawingCache(boolean)
7285 */
7286 public void buildDrawingCache() {
7287 buildDrawingCache(false);
7288 }
7289
7290 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007291 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
7292 *
7293 * <p>If you call {@link #buildDrawingCache()} manually without calling
7294 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7295 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007296 *
7297 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7298 * this method will create a bitmap of the same size as this view. Because this bitmap
7299 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7300 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7301 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7302 * size than the view. This implies that your application must be able to handle this
7303 * size.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007304 *
7305 * @see #getDrawingCache()
7306 * @see #destroyDrawingCache()
7307 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007308 public void buildDrawingCache(boolean autoScale) {
7309 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07007310 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007311
7312 if (ViewDebug.TRACE_HIERARCHY) {
7313 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
7314 }
Romain Guy13922e02009-05-12 17:56:14 -07007315 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007316 EventLog.writeEvent(60002, hashCode());
7317 }
7318
Romain Guy8506ab42009-06-11 17:35:47 -07007319 int width = mRight - mLeft;
7320 int height = mBottom - mTop;
7321
7322 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07007323 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07007324
Romain Guye1123222009-06-29 14:24:56 -07007325 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007326 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
7327 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07007328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007329
7330 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07007331 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Romain Guya62e4702009-10-08 10:48:54 -07007332 final boolean translucentWindow = attachInfo != null && attachInfo.mTranslucentWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007333
7334 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07007335 // Projected bitmap size in bytes
7336 (width * height * (opaque && !translucentWindow ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007337 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
7338 destroyDrawingCache();
7339 return;
7340 }
7341
7342 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07007343 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344
7345 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007346 Bitmap.Config quality;
7347 if (!opaque) {
7348 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
7349 case DRAWING_CACHE_QUALITY_AUTO:
7350 quality = Bitmap.Config.ARGB_8888;
7351 break;
7352 case DRAWING_CACHE_QUALITY_LOW:
7353 quality = Bitmap.Config.ARGB_4444;
7354 break;
7355 case DRAWING_CACHE_QUALITY_HIGH:
7356 quality = Bitmap.Config.ARGB_8888;
7357 break;
7358 default:
7359 quality = Bitmap.Config.ARGB_8888;
7360 break;
7361 }
7362 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07007363 // Optimization for translucent windows
7364 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
7365 quality = translucentWindow ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007366 }
7367
7368 // Try to cleanup memory
7369 if (bitmap != null) bitmap.recycle();
7370
7371 try {
7372 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07007373 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07007374 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07007375 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007376 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07007377 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007378 }
Romain Guy35b38ce2009-10-07 13:38:55 -07007379 if (opaque && translucentWindow) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007380 } catch (OutOfMemoryError e) {
7381 // If there is not enough memory to create the bitmap cache, just
7382 // ignore the issue as bitmap caches are not required to draw the
7383 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07007384 if (autoScale) {
7385 mDrawingCache = null;
7386 } else {
7387 mUnscaledDrawingCache = null;
7388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007389 return;
7390 }
7391
7392 clear = drawingCacheBackgroundColor != 0;
7393 }
7394
7395 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007396 if (attachInfo != null) {
7397 canvas = attachInfo.mCanvas;
7398 if (canvas == null) {
7399 canvas = new Canvas();
7400 }
7401 canvas.setBitmap(bitmap);
7402 // Temporarily clobber the cached Canvas in case one of our children
7403 // is also using a drawing cache. Without this, the children would
7404 // steal the canvas by attaching their own bitmap to it and bad, bad
7405 // thing would happen (invisible views, corrupted drawings, etc.)
7406 attachInfo.mCanvas = null;
7407 } else {
7408 // This case should hopefully never or seldom happen
7409 canvas = new Canvas(bitmap);
7410 }
7411
7412 if (clear) {
7413 bitmap.eraseColor(drawingCacheBackgroundColor);
7414 }
7415
7416 computeScroll();
7417 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07007418
Romain Guye1123222009-06-29 14:24:56 -07007419 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007420 final float scale = attachInfo.mApplicationScale;
7421 canvas.scale(scale, scale);
7422 }
7423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007424 canvas.translate(-mScrollX, -mScrollY);
7425
Romain Guy5bcdff42009-05-14 21:27:18 -07007426 mPrivateFlags |= DRAWN;
Romain Guyecd80ee2009-12-03 17:13:02 -08007427 mPrivateFlags |= DRAWING_CACHE_VALID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007428
7429 // Fast path for layouts with no backgrounds
7430 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7431 if (ViewDebug.TRACE_HIERARCHY) {
7432 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7433 }
Romain Guy5bcdff42009-05-14 21:27:18 -07007434 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007435 dispatchDraw(canvas);
7436 } else {
7437 draw(canvas);
7438 }
7439
7440 canvas.restoreToCount(restoreCount);
7441
7442 if (attachInfo != null) {
7443 // Restore the cached Canvas for our siblings
7444 attachInfo.mCanvas = canvas;
7445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007446 }
7447 }
7448
7449 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007450 * Create a snapshot of the view into a bitmap. We should probably make
7451 * some form of this public, but should think about the API.
7452 */
Romain Guy223ff5c2010-03-02 17:07:47 -08007453 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007454 int width = mRight - mLeft;
7455 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007456
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007457 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07007458 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007459 width = (int) ((width * scale) + 0.5f);
7460 height = (int) ((height * scale) + 0.5f);
7461
Romain Guy8c11e312009-09-14 15:15:30 -07007462 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007463 if (bitmap == null) {
7464 throw new OutOfMemoryError();
7465 }
7466
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007467 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
7468
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007469 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007470 if (attachInfo != null) {
7471 canvas = attachInfo.mCanvas;
7472 if (canvas == null) {
7473 canvas = new Canvas();
7474 }
7475 canvas.setBitmap(bitmap);
7476 // Temporarily clobber the cached Canvas in case one of our children
7477 // is also using a drawing cache. Without this, the children would
7478 // steal the canvas by attaching their own bitmap to it and bad, bad
7479 // things would happen (invisible views, corrupted drawings, etc.)
7480 attachInfo.mCanvas = null;
7481 } else {
7482 // This case should hopefully never or seldom happen
7483 canvas = new Canvas(bitmap);
7484 }
7485
Romain Guy5bcdff42009-05-14 21:27:18 -07007486 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007487 bitmap.eraseColor(backgroundColor);
7488 }
7489
7490 computeScroll();
7491 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007492 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007493 canvas.translate(-mScrollX, -mScrollY);
7494
Romain Guy5bcdff42009-05-14 21:27:18 -07007495 // Temporarily remove the dirty mask
7496 int flags = mPrivateFlags;
7497 mPrivateFlags &= ~DIRTY_MASK;
7498
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007499 // Fast path for layouts with no backgrounds
7500 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7501 dispatchDraw(canvas);
7502 } else {
7503 draw(canvas);
7504 }
7505
Romain Guy5bcdff42009-05-14 21:27:18 -07007506 mPrivateFlags = flags;
7507
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007508 canvas.restoreToCount(restoreCount);
7509
7510 if (attachInfo != null) {
7511 // Restore the cached Canvas for our siblings
7512 attachInfo.mCanvas = canvas;
7513 }
Romain Guy8506ab42009-06-11 17:35:47 -07007514
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007515 return bitmap;
7516 }
7517
7518 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007519 * Indicates whether this View is currently in edit mode. A View is usually
7520 * in edit mode when displayed within a developer tool. For instance, if
7521 * this View is being drawn by a visual user interface builder, this method
7522 * should return true.
7523 *
7524 * Subclasses should check the return value of this method to provide
7525 * different behaviors if their normal behavior might interfere with the
7526 * host environment. For instance: the class spawns a thread in its
7527 * constructor, the drawing code relies on device-specific features, etc.
7528 *
7529 * This method is usually checked in the drawing code of custom widgets.
7530 *
7531 * @return True if this View is in edit mode, false otherwise.
7532 */
7533 public boolean isInEditMode() {
7534 return false;
7535 }
7536
7537 /**
7538 * If the View draws content inside its padding and enables fading edges,
7539 * it needs to support padding offsets. Padding offsets are added to the
7540 * fading edges to extend the length of the fade so that it covers pixels
7541 * drawn inside the padding.
7542 *
7543 * Subclasses of this class should override this method if they need
7544 * to draw content inside the padding.
7545 *
7546 * @return True if padding offset must be applied, false otherwise.
7547 *
7548 * @see #getLeftPaddingOffset()
7549 * @see #getRightPaddingOffset()
7550 * @see #getTopPaddingOffset()
7551 * @see #getBottomPaddingOffset()
7552 *
7553 * @since CURRENT
7554 */
7555 protected boolean isPaddingOffsetRequired() {
7556 return false;
7557 }
7558
7559 /**
7560 * Amount by which to extend the left fading region. Called only when
7561 * {@link #isPaddingOffsetRequired()} returns true.
7562 *
7563 * @return The left padding offset in pixels.
7564 *
7565 * @see #isPaddingOffsetRequired()
7566 *
7567 * @since CURRENT
7568 */
7569 protected int getLeftPaddingOffset() {
7570 return 0;
7571 }
7572
7573 /**
7574 * Amount by which to extend the right fading region. Called only when
7575 * {@link #isPaddingOffsetRequired()} returns true.
7576 *
7577 * @return The right padding offset in pixels.
7578 *
7579 * @see #isPaddingOffsetRequired()
7580 *
7581 * @since CURRENT
7582 */
7583 protected int getRightPaddingOffset() {
7584 return 0;
7585 }
7586
7587 /**
7588 * Amount by which to extend the top fading region. Called only when
7589 * {@link #isPaddingOffsetRequired()} returns true.
7590 *
7591 * @return The top padding offset in pixels.
7592 *
7593 * @see #isPaddingOffsetRequired()
7594 *
7595 * @since CURRENT
7596 */
7597 protected int getTopPaddingOffset() {
7598 return 0;
7599 }
7600
7601 /**
7602 * Amount by which to extend the bottom fading region. Called only when
7603 * {@link #isPaddingOffsetRequired()} returns true.
7604 *
7605 * @return The bottom padding offset in pixels.
7606 *
7607 * @see #isPaddingOffsetRequired()
7608 *
7609 * @since CURRENT
7610 */
7611 protected int getBottomPaddingOffset() {
7612 return 0;
7613 }
7614
7615 /**
7616 * Manually render this view (and all of its children) to the given Canvas.
7617 * The view must have already done a full layout before this function is
7618 * called. When implementing a view, do not override this method; instead,
7619 * you should implement {@link #onDraw}.
7620 *
7621 * @param canvas The Canvas to which the View is rendered.
7622 */
7623 public void draw(Canvas canvas) {
7624 if (ViewDebug.TRACE_HIERARCHY) {
7625 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7626 }
7627
Romain Guy5bcdff42009-05-14 21:27:18 -07007628 final int privateFlags = mPrivateFlags;
7629 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
7630 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
7631 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07007632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007633 /*
7634 * Draw traversal performs several drawing steps which must be executed
7635 * in the appropriate order:
7636 *
7637 * 1. Draw the background
7638 * 2. If necessary, save the canvas' layers to prepare for fading
7639 * 3. Draw view's content
7640 * 4. Draw children
7641 * 5. If necessary, draw the fading edges and restore layers
7642 * 6. Draw decorations (scrollbars for instance)
7643 */
7644
7645 // Step 1, draw the background, if needed
7646 int saveCount;
7647
Romain Guy24443ea2009-05-11 11:56:30 -07007648 if (!dirtyOpaque) {
7649 final Drawable background = mBGDrawable;
7650 if (background != null) {
7651 final int scrollX = mScrollX;
7652 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007653
Romain Guy24443ea2009-05-11 11:56:30 -07007654 if (mBackgroundSizeChanged) {
7655 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
7656 mBackgroundSizeChanged = false;
7657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007658
Romain Guy24443ea2009-05-11 11:56:30 -07007659 if ((scrollX | scrollY) == 0) {
7660 background.draw(canvas);
7661 } else {
7662 canvas.translate(scrollX, scrollY);
7663 background.draw(canvas);
7664 canvas.translate(-scrollX, -scrollY);
7665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007666 }
7667 }
7668
7669 // skip step 2 & 5 if possible (common case)
7670 final int viewFlags = mViewFlags;
7671 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
7672 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
7673 if (!verticalEdges && !horizontalEdges) {
7674 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007675 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007676
7677 // Step 4, draw the children
7678 dispatchDraw(canvas);
7679
7680 // Step 6, draw decorations (scrollbars)
7681 onDrawScrollBars(canvas);
7682
7683 // we're done...
7684 return;
7685 }
7686
7687 /*
7688 * Here we do the full fledged routine...
7689 * (this is an uncommon case where speed matters less,
7690 * this is why we repeat some of the tests that have been
7691 * done above)
7692 */
7693
7694 boolean drawTop = false;
7695 boolean drawBottom = false;
7696 boolean drawLeft = false;
7697 boolean drawRight = false;
7698
7699 float topFadeStrength = 0.0f;
7700 float bottomFadeStrength = 0.0f;
7701 float leftFadeStrength = 0.0f;
7702 float rightFadeStrength = 0.0f;
7703
7704 // Step 2, save the canvas' layers
7705 int paddingLeft = mPaddingLeft;
7706 int paddingTop = mPaddingTop;
7707
7708 final boolean offsetRequired = isPaddingOffsetRequired();
7709 if (offsetRequired) {
7710 paddingLeft += getLeftPaddingOffset();
7711 paddingTop += getTopPaddingOffset();
7712 }
7713
7714 int left = mScrollX + paddingLeft;
7715 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
7716 int top = mScrollY + paddingTop;
7717 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
7718
7719 if (offsetRequired) {
7720 right += getRightPaddingOffset();
7721 bottom += getBottomPaddingOffset();
7722 }
7723
7724 final ScrollabilityCache scrollabilityCache = mScrollCache;
7725 int length = scrollabilityCache.fadingEdgeLength;
7726
7727 // clip the fade length if top and bottom fades overlap
7728 // overlapping fades produce odd-looking artifacts
7729 if (verticalEdges && (top + length > bottom - length)) {
7730 length = (bottom - top) / 2;
7731 }
7732
7733 // also clip horizontal fades if necessary
7734 if (horizontalEdges && (left + length > right - length)) {
7735 length = (right - left) / 2;
7736 }
7737
7738 if (verticalEdges) {
7739 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007740 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007741 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007742 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007743 }
7744
7745 if (horizontalEdges) {
7746 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007747 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007749 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007750 }
7751
7752 saveCount = canvas.getSaveCount();
7753
7754 int solidColor = getSolidColor();
7755 if (solidColor == 0) {
7756 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
7757
7758 if (drawTop) {
7759 canvas.saveLayer(left, top, right, top + length, null, flags);
7760 }
7761
7762 if (drawBottom) {
7763 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
7764 }
7765
7766 if (drawLeft) {
7767 canvas.saveLayer(left, top, left + length, bottom, null, flags);
7768 }
7769
7770 if (drawRight) {
7771 canvas.saveLayer(right - length, top, right, bottom, null, flags);
7772 }
7773 } else {
7774 scrollabilityCache.setFadeColor(solidColor);
7775 }
7776
7777 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007778 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779
7780 // Step 4, draw the children
7781 dispatchDraw(canvas);
7782
7783 // Step 5, draw the fade effect and restore layers
7784 final Paint p = scrollabilityCache.paint;
7785 final Matrix matrix = scrollabilityCache.matrix;
7786 final Shader fade = scrollabilityCache.shader;
7787 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
7788
7789 if (drawTop) {
7790 matrix.setScale(1, fadeHeight * topFadeStrength);
7791 matrix.postTranslate(left, top);
7792 fade.setLocalMatrix(matrix);
7793 canvas.drawRect(left, top, right, top + length, p);
7794 }
7795
7796 if (drawBottom) {
7797 matrix.setScale(1, fadeHeight * bottomFadeStrength);
7798 matrix.postRotate(180);
7799 matrix.postTranslate(left, bottom);
7800 fade.setLocalMatrix(matrix);
7801 canvas.drawRect(left, bottom - length, right, bottom, p);
7802 }
7803
7804 if (drawLeft) {
7805 matrix.setScale(1, fadeHeight * leftFadeStrength);
7806 matrix.postRotate(-90);
7807 matrix.postTranslate(left, top);
7808 fade.setLocalMatrix(matrix);
7809 canvas.drawRect(left, top, left + length, bottom, p);
7810 }
7811
7812 if (drawRight) {
7813 matrix.setScale(1, fadeHeight * rightFadeStrength);
7814 matrix.postRotate(90);
7815 matrix.postTranslate(right, top);
7816 fade.setLocalMatrix(matrix);
7817 canvas.drawRect(right - length, top, right, bottom, p);
7818 }
7819
7820 canvas.restoreToCount(saveCount);
7821
7822 // Step 6, draw decorations (scrollbars)
7823 onDrawScrollBars(canvas);
7824 }
7825
7826 /**
7827 * Override this if your view is known to always be drawn on top of a solid color background,
7828 * and needs to draw fading edges. Returning a non-zero color enables the view system to
7829 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
7830 * should be set to 0xFF.
7831 *
7832 * @see #setVerticalFadingEdgeEnabled
7833 * @see #setHorizontalFadingEdgeEnabled
7834 *
7835 * @return The known solid color background for this view, or 0 if the color may vary
7836 */
7837 public int getSolidColor() {
7838 return 0;
7839 }
7840
7841 /**
7842 * Build a human readable string representation of the specified view flags.
7843 *
7844 * @param flags the view flags to convert to a string
7845 * @return a String representing the supplied flags
7846 */
7847 private static String printFlags(int flags) {
7848 String output = "";
7849 int numFlags = 0;
7850 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
7851 output += "TAKES_FOCUS";
7852 numFlags++;
7853 }
7854
7855 switch (flags & VISIBILITY_MASK) {
7856 case INVISIBLE:
7857 if (numFlags > 0) {
7858 output += " ";
7859 }
7860 output += "INVISIBLE";
7861 // USELESS HERE numFlags++;
7862 break;
7863 case GONE:
7864 if (numFlags > 0) {
7865 output += " ";
7866 }
7867 output += "GONE";
7868 // USELESS HERE numFlags++;
7869 break;
7870 default:
7871 break;
7872 }
7873 return output;
7874 }
7875
7876 /**
7877 * Build a human readable string representation of the specified private
7878 * view flags.
7879 *
7880 * @param privateFlags the private view flags to convert to a string
7881 * @return a String representing the supplied flags
7882 */
7883 private static String printPrivateFlags(int privateFlags) {
7884 String output = "";
7885 int numFlags = 0;
7886
7887 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
7888 output += "WANTS_FOCUS";
7889 numFlags++;
7890 }
7891
7892 if ((privateFlags & FOCUSED) == FOCUSED) {
7893 if (numFlags > 0) {
7894 output += " ";
7895 }
7896 output += "FOCUSED";
7897 numFlags++;
7898 }
7899
7900 if ((privateFlags & SELECTED) == SELECTED) {
7901 if (numFlags > 0) {
7902 output += " ";
7903 }
7904 output += "SELECTED";
7905 numFlags++;
7906 }
7907
7908 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
7909 if (numFlags > 0) {
7910 output += " ";
7911 }
7912 output += "IS_ROOT_NAMESPACE";
7913 numFlags++;
7914 }
7915
7916 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
7917 if (numFlags > 0) {
7918 output += " ";
7919 }
7920 output += "HAS_BOUNDS";
7921 numFlags++;
7922 }
7923
7924 if ((privateFlags & DRAWN) == DRAWN) {
7925 if (numFlags > 0) {
7926 output += " ";
7927 }
7928 output += "DRAWN";
7929 // USELESS HERE numFlags++;
7930 }
7931 return output;
7932 }
7933
7934 /**
7935 * <p>Indicates whether or not this view's layout will be requested during
7936 * the next hierarchy layout pass.</p>
7937 *
7938 * @return true if the layout will be forced during next layout pass
7939 */
7940 public boolean isLayoutRequested() {
7941 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
7942 }
7943
7944 /**
7945 * Assign a size and position to a view and all of its
7946 * descendants
7947 *
7948 * <p>This is the second phase of the layout mechanism.
7949 * (The first is measuring). In this phase, each parent calls
7950 * layout on all of its children to position them.
7951 * This is typically done using the child measurements
7952 * that were stored in the measure pass().
7953 *
7954 * Derived classes with children should override
7955 * onLayout. In that method, they should
Chet Haase21cd1382010-09-01 17:42:29 -07007956 * call layout on each of their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 *
7958 * @param l Left position, relative to parent
7959 * @param t Top position, relative to parent
7960 * @param r Right position, relative to parent
7961 * @param b Bottom position, relative to parent
7962 */
7963 public final void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07007964 int oldL = mLeft;
7965 int oldT = mTop;
7966 int oldB = mBottom;
7967 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 boolean changed = setFrame(l, t, r, b);
7969 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
7970 if (ViewDebug.TRACE_HIERARCHY) {
7971 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
7972 }
7973
7974 onLayout(changed, l, t, r, b);
7975 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07007976
7977 if (mOnLayoutChangeListeners != null) {
7978 ArrayList<OnLayoutChangeListener> listenersCopy =
7979 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
7980 int numListeners = listenersCopy.size();
7981 for (int i = 0; i < numListeners; ++i) {
7982 listenersCopy.get(i).onLayoutChange(this, l, r, t, b, oldL, oldT, oldR, oldB);
7983 }
7984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007985 }
7986 mPrivateFlags &= ~FORCE_LAYOUT;
7987 }
7988
7989 /**
7990 * Called from layout when this view should
7991 * assign a size and position to each of its children.
7992 *
7993 * Derived classes with children should override
7994 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07007995 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 * @param changed This is a new size or position for this view
7997 * @param left Left position, relative to parent
7998 * @param top Top position, relative to parent
7999 * @param right Right position, relative to parent
8000 * @param bottom Bottom position, relative to parent
8001 */
8002 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8003 }
8004
8005 /**
8006 * Assign a size and position to this view.
8007 *
8008 * This is called from layout.
8009 *
8010 * @param left Left position, relative to parent
8011 * @param top Top position, relative to parent
8012 * @param right Right position, relative to parent
8013 * @param bottom Bottom position, relative to parent
8014 * @return true if the new size and position are different than the
8015 * previous ones
8016 * {@hide}
8017 */
8018 protected boolean setFrame(int left, int top, int right, int bottom) {
8019 boolean changed = false;
8020
8021 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008022 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008023 + right + "," + bottom + ")");
8024 }
8025
8026 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8027 changed = true;
8028
8029 // Remember our drawn bit
8030 int drawn = mPrivateFlags & DRAWN;
8031
8032 // Invalidate our old position
8033 invalidate();
8034
8035
8036 int oldWidth = mRight - mLeft;
8037 int oldHeight = mBottom - mTop;
8038
8039 mLeft = left;
8040 mTop = top;
8041 mRight = right;
8042 mBottom = bottom;
8043
8044 mPrivateFlags |= HAS_BOUNDS;
8045
8046 int newWidth = right - left;
8047 int newHeight = bottom - top;
8048
8049 if (newWidth != oldWidth || newHeight != oldHeight) {
8050 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8051 }
8052
8053 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8054 // If we are visible, force the DRAWN bit to on so that
8055 // this invalidate will go through (at least to our parent).
8056 // This is because someone may have invalidated this view
8057 // before this call to setFrame came in, therby clearing
8058 // the DRAWN bit.
8059 mPrivateFlags |= DRAWN;
8060 invalidate();
8061 }
8062
8063 // Reset drawn bit to original value (invalidate turns it off)
8064 mPrivateFlags |= drawn;
8065
8066 mBackgroundSizeChanged = true;
8067 }
8068 return changed;
8069 }
8070
8071 /**
8072 * Finalize inflating a view from XML. This is called as the last phase
8073 * of inflation, after all child views have been added.
8074 *
8075 * <p>Even if the subclass overrides onFinishInflate, they should always be
8076 * sure to call the super method, so that we get called.
8077 */
8078 protected void onFinishInflate() {
8079 }
8080
8081 /**
8082 * Returns the resources associated with this view.
8083 *
8084 * @return Resources object.
8085 */
8086 public Resources getResources() {
8087 return mResources;
8088 }
8089
8090 /**
8091 * Invalidates the specified Drawable.
8092 *
8093 * @param drawable the drawable to invalidate
8094 */
8095 public void invalidateDrawable(Drawable drawable) {
8096 if (verifyDrawable(drawable)) {
8097 final Rect dirty = drawable.getBounds();
8098 final int scrollX = mScrollX;
8099 final int scrollY = mScrollY;
8100
8101 invalidate(dirty.left + scrollX, dirty.top + scrollY,
8102 dirty.right + scrollX, dirty.bottom + scrollY);
8103 }
8104 }
8105
8106 /**
8107 * Schedules an action on a drawable to occur at a specified time.
8108 *
8109 * @param who the recipient of the action
8110 * @param what the action to run on the drawable
8111 * @param when the time at which the action must occur. Uses the
8112 * {@link SystemClock#uptimeMillis} timebase.
8113 */
8114 public void scheduleDrawable(Drawable who, Runnable what, long when) {
8115 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8116 mAttachInfo.mHandler.postAtTime(what, who, when);
8117 }
8118 }
8119
8120 /**
8121 * Cancels a scheduled action on a drawable.
8122 *
8123 * @param who the recipient of the action
8124 * @param what the action to cancel
8125 */
8126 public void unscheduleDrawable(Drawable who, Runnable what) {
8127 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8128 mAttachInfo.mHandler.removeCallbacks(what, who);
8129 }
8130 }
8131
8132 /**
8133 * Unschedule any events associated with the given Drawable. This can be
8134 * used when selecting a new Drawable into a view, so that the previous
8135 * one is completely unscheduled.
8136 *
8137 * @param who The Drawable to unschedule.
8138 *
8139 * @see #drawableStateChanged
8140 */
8141 public void unscheduleDrawable(Drawable who) {
8142 if (mAttachInfo != null) {
8143 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
8144 }
8145 }
8146
8147 /**
8148 * If your view subclass is displaying its own Drawable objects, it should
8149 * override this function and return true for any Drawable it is
8150 * displaying. This allows animations for those drawables to be
8151 * scheduled.
8152 *
8153 * <p>Be sure to call through to the super class when overriding this
8154 * function.
8155 *
8156 * @param who The Drawable to verify. Return true if it is one you are
8157 * displaying, else return the result of calling through to the
8158 * super class.
8159 *
8160 * @return boolean If true than the Drawable is being displayed in the
8161 * view; else false and it is not allowed to animate.
8162 *
8163 * @see #unscheduleDrawable
8164 * @see #drawableStateChanged
8165 */
8166 protected boolean verifyDrawable(Drawable who) {
8167 return who == mBGDrawable;
8168 }
8169
8170 /**
8171 * This function is called whenever the state of the view changes in such
8172 * a way that it impacts the state of drawables being shown.
8173 *
8174 * <p>Be sure to call through to the superclass when overriding this
8175 * function.
8176 *
8177 * @see Drawable#setState
8178 */
8179 protected void drawableStateChanged() {
8180 Drawable d = mBGDrawable;
8181 if (d != null && d.isStateful()) {
8182 d.setState(getDrawableState());
8183 }
8184 }
8185
8186 /**
8187 * Call this to force a view to update its drawable state. This will cause
8188 * drawableStateChanged to be called on this view. Views that are interested
8189 * in the new state should call getDrawableState.
8190 *
8191 * @see #drawableStateChanged
8192 * @see #getDrawableState
8193 */
8194 public void refreshDrawableState() {
8195 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
8196 drawableStateChanged();
8197
8198 ViewParent parent = mParent;
8199 if (parent != null) {
8200 parent.childDrawableStateChanged(this);
8201 }
8202 }
8203
8204 /**
8205 * Return an array of resource IDs of the drawable states representing the
8206 * current state of the view.
8207 *
8208 * @return The current drawable state
8209 *
8210 * @see Drawable#setState
8211 * @see #drawableStateChanged
8212 * @see #onCreateDrawableState
8213 */
8214 public final int[] getDrawableState() {
8215 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
8216 return mDrawableState;
8217 } else {
8218 mDrawableState = onCreateDrawableState(0);
8219 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
8220 return mDrawableState;
8221 }
8222 }
8223
8224 /**
8225 * Generate the new {@link android.graphics.drawable.Drawable} state for
8226 * this view. This is called by the view
8227 * system when the cached Drawable state is determined to be invalid. To
8228 * retrieve the current state, you should use {@link #getDrawableState}.
8229 *
8230 * @param extraSpace if non-zero, this is the number of extra entries you
8231 * would like in the returned array in which you can place your own
8232 * states.
8233 *
8234 * @return Returns an array holding the current {@link Drawable} state of
8235 * the view.
8236 *
8237 * @see #mergeDrawableStates
8238 */
8239 protected int[] onCreateDrawableState(int extraSpace) {
8240 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
8241 mParent instanceof View) {
8242 return ((View) mParent).onCreateDrawableState(extraSpace);
8243 }
8244
8245 int[] drawableState;
8246
8247 int privateFlags = mPrivateFlags;
8248
8249 int viewStateIndex = (((privateFlags & PRESSED) != 0) ? 1 : 0);
8250
8251 viewStateIndex = (viewStateIndex << 1)
8252 + (((mViewFlags & ENABLED_MASK) == ENABLED) ? 1 : 0);
8253
8254 viewStateIndex = (viewStateIndex << 1) + (isFocused() ? 1 : 0);
8255
8256 viewStateIndex = (viewStateIndex << 1)
8257 + (((privateFlags & SELECTED) != 0) ? 1 : 0);
8258
8259 final boolean hasWindowFocus = hasWindowFocus();
8260 viewStateIndex = (viewStateIndex << 1) + (hasWindowFocus ? 1 : 0);
8261
8262 drawableState = VIEW_STATE_SETS[viewStateIndex];
8263
8264 //noinspection ConstantIfStatement
8265 if (false) {
8266 Log.i("View", "drawableStateIndex=" + viewStateIndex);
8267 Log.i("View", toString()
8268 + " pressed=" + ((privateFlags & PRESSED) != 0)
8269 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
8270 + " fo=" + hasFocus()
8271 + " sl=" + ((privateFlags & SELECTED) != 0)
8272 + " wf=" + hasWindowFocus
8273 + ": " + Arrays.toString(drawableState));
8274 }
8275
8276 if (extraSpace == 0) {
8277 return drawableState;
8278 }
8279
8280 final int[] fullState;
8281 if (drawableState != null) {
8282 fullState = new int[drawableState.length + extraSpace];
8283 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
8284 } else {
8285 fullState = new int[extraSpace];
8286 }
8287
8288 return fullState;
8289 }
8290
8291 /**
8292 * Merge your own state values in <var>additionalState</var> into the base
8293 * state values <var>baseState</var> that were returned by
8294 * {@link #onCreateDrawableState}.
8295 *
8296 * @param baseState The base state values returned by
8297 * {@link #onCreateDrawableState}, which will be modified to also hold your
8298 * own additional state values.
8299 *
8300 * @param additionalState The additional state values you would like
8301 * added to <var>baseState</var>; this array is not modified.
8302 *
8303 * @return As a convenience, the <var>baseState</var> array you originally
8304 * passed into the function is returned.
8305 *
8306 * @see #onCreateDrawableState
8307 */
8308 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
8309 final int N = baseState.length;
8310 int i = N - 1;
8311 while (i >= 0 && baseState[i] == 0) {
8312 i--;
8313 }
8314 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
8315 return baseState;
8316 }
8317
8318 /**
8319 * Sets the background color for this view.
8320 * @param color the color of the background
8321 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008322 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008323 public void setBackgroundColor(int color) {
8324 setBackgroundDrawable(new ColorDrawable(color));
8325 }
8326
8327 /**
8328 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07008329 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008330 * @param resid The identifier of the resource.
8331 * @attr ref android.R.styleable#View_background
8332 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008333 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008334 public void setBackgroundResource(int resid) {
8335 if (resid != 0 && resid == mBackgroundResource) {
8336 return;
8337 }
8338
8339 Drawable d= null;
8340 if (resid != 0) {
8341 d = mResources.getDrawable(resid);
8342 }
8343 setBackgroundDrawable(d);
8344
8345 mBackgroundResource = resid;
8346 }
8347
8348 /**
8349 * Set the background to a given Drawable, or remove the background. If the
8350 * background has padding, this View's padding is set to the background's
8351 * padding. However, when a background is removed, this View's padding isn't
8352 * touched. If setting the padding is desired, please use
8353 * {@link #setPadding(int, int, int, int)}.
8354 *
8355 * @param d The Drawable to use as the background, or null to remove the
8356 * background
8357 */
8358 public void setBackgroundDrawable(Drawable d) {
8359 boolean requestLayout = false;
8360
8361 mBackgroundResource = 0;
8362
8363 /*
8364 * Regardless of whether we're setting a new background or not, we want
8365 * to clear the previous drawable.
8366 */
8367 if (mBGDrawable != null) {
8368 mBGDrawable.setCallback(null);
8369 unscheduleDrawable(mBGDrawable);
8370 }
8371
8372 if (d != null) {
8373 Rect padding = sThreadLocal.get();
8374 if (padding == null) {
8375 padding = new Rect();
8376 sThreadLocal.set(padding);
8377 }
8378 if (d.getPadding(padding)) {
8379 setPadding(padding.left, padding.top, padding.right, padding.bottom);
8380 }
8381
8382 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
8383 // if it has a different minimum size, we should layout again
8384 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
8385 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
8386 requestLayout = true;
8387 }
8388
8389 d.setCallback(this);
8390 if (d.isStateful()) {
8391 d.setState(getDrawableState());
8392 }
8393 d.setVisible(getVisibility() == VISIBLE, false);
8394 mBGDrawable = d;
8395
8396 if ((mPrivateFlags & SKIP_DRAW) != 0) {
8397 mPrivateFlags &= ~SKIP_DRAW;
8398 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8399 requestLayout = true;
8400 }
8401 } else {
8402 /* Remove the background */
8403 mBGDrawable = null;
8404
8405 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
8406 /*
8407 * This view ONLY drew the background before and we're removing
8408 * the background, so now it won't draw anything
8409 * (hence we SKIP_DRAW)
8410 */
8411 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
8412 mPrivateFlags |= SKIP_DRAW;
8413 }
8414
8415 /*
8416 * When the background is set, we try to apply its padding to this
8417 * View. When the background is removed, we don't touch this View's
8418 * padding. This is noted in the Javadocs. Hence, we don't need to
8419 * requestLayout(), the invalidate() below is sufficient.
8420 */
8421
8422 // The old background's minimum size could have affected this
8423 // View's layout, so let's requestLayout
8424 requestLayout = true;
8425 }
8426
Romain Guy8f1344f52009-05-15 16:03:59 -07008427 computeOpaqueFlags();
8428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008429 if (requestLayout) {
8430 requestLayout();
8431 }
8432
8433 mBackgroundSizeChanged = true;
8434 invalidate();
8435 }
8436
8437 /**
8438 * Gets the background drawable
8439 * @return The drawable used as the background for this view, if any.
8440 */
8441 public Drawable getBackground() {
8442 return mBGDrawable;
8443 }
8444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008445 /**
8446 * Sets the padding. The view may add on the space required to display
8447 * the scrollbars, depending on the style and visibility of the scrollbars.
8448 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
8449 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
8450 * from the values set in this call.
8451 *
8452 * @attr ref android.R.styleable#View_padding
8453 * @attr ref android.R.styleable#View_paddingBottom
8454 * @attr ref android.R.styleable#View_paddingLeft
8455 * @attr ref android.R.styleable#View_paddingRight
8456 * @attr ref android.R.styleable#View_paddingTop
8457 * @param left the left padding in pixels
8458 * @param top the top padding in pixels
8459 * @param right the right padding in pixels
8460 * @param bottom the bottom padding in pixels
8461 */
8462 public void setPadding(int left, int top, int right, int bottom) {
8463 boolean changed = false;
8464
8465 mUserPaddingRight = right;
8466 mUserPaddingBottom = bottom;
8467
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008468 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07008469
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008470 // Common case is there are no scroll bars.
8471 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
8472 // TODO: Deal with RTL languages to adjust left padding instead of right.
8473 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
8474 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8475 ? 0 : getVerticalScrollbarWidth();
8476 }
8477 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
8478 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8479 ? 0 : getHorizontalScrollbarHeight();
8480 }
8481 }
Romain Guy8506ab42009-06-11 17:35:47 -07008482
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008483 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008484 changed = true;
8485 mPaddingLeft = left;
8486 }
8487 if (mPaddingTop != top) {
8488 changed = true;
8489 mPaddingTop = top;
8490 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008491 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008492 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008493 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008495 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008496 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008497 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008498 }
8499
8500 if (changed) {
8501 requestLayout();
8502 }
8503 }
8504
8505 /**
8506 * Returns the top padding of this view.
8507 *
8508 * @return the top padding in pixels
8509 */
8510 public int getPaddingTop() {
8511 return mPaddingTop;
8512 }
8513
8514 /**
8515 * Returns the bottom padding of this view. If there are inset and enabled
8516 * scrollbars, this value may include the space required to display the
8517 * scrollbars as well.
8518 *
8519 * @return the bottom padding in pixels
8520 */
8521 public int getPaddingBottom() {
8522 return mPaddingBottom;
8523 }
8524
8525 /**
8526 * Returns the left padding of this view. If there are inset and enabled
8527 * scrollbars, this value may include the space required to display the
8528 * scrollbars as well.
8529 *
8530 * @return the left padding in pixels
8531 */
8532 public int getPaddingLeft() {
8533 return mPaddingLeft;
8534 }
8535
8536 /**
8537 * Returns the right padding of this view. If there are inset and enabled
8538 * scrollbars, this value may include the space required to display the
8539 * scrollbars as well.
8540 *
8541 * @return the right padding in pixels
8542 */
8543 public int getPaddingRight() {
8544 return mPaddingRight;
8545 }
8546
8547 /**
8548 * Changes the selection state of this view. A view can be selected or not.
8549 * Note that selection is not the same as focus. Views are typically
8550 * selected in the context of an AdapterView like ListView or GridView;
8551 * the selected view is the view that is highlighted.
8552 *
8553 * @param selected true if the view must be selected, false otherwise
8554 */
8555 public void setSelected(boolean selected) {
8556 if (((mPrivateFlags & SELECTED) != 0) != selected) {
8557 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07008558 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008559 invalidate();
8560 refreshDrawableState();
8561 dispatchSetSelected(selected);
8562 }
8563 }
8564
8565 /**
8566 * Dispatch setSelected to all of this View's children.
8567 *
8568 * @see #setSelected(boolean)
8569 *
8570 * @param selected The new selected state
8571 */
8572 protected void dispatchSetSelected(boolean selected) {
8573 }
8574
8575 /**
8576 * Indicates the selection state of this view.
8577 *
8578 * @return true if the view is selected, false otherwise
8579 */
8580 @ViewDebug.ExportedProperty
8581 public boolean isSelected() {
8582 return (mPrivateFlags & SELECTED) != 0;
8583 }
8584
8585 /**
8586 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
8587 * observer can be used to get notifications when global events, like
8588 * layout, happen.
8589 *
8590 * The returned ViewTreeObserver observer is not guaranteed to remain
8591 * valid for the lifetime of this View. If the caller of this method keeps
8592 * a long-lived reference to ViewTreeObserver, it should always check for
8593 * the return value of {@link ViewTreeObserver#isAlive()}.
8594 *
8595 * @return The ViewTreeObserver for this view's hierarchy.
8596 */
8597 public ViewTreeObserver getViewTreeObserver() {
8598 if (mAttachInfo != null) {
8599 return mAttachInfo.mTreeObserver;
8600 }
8601 if (mFloatingTreeObserver == null) {
8602 mFloatingTreeObserver = new ViewTreeObserver();
8603 }
8604 return mFloatingTreeObserver;
8605 }
8606
8607 /**
8608 * <p>Finds the topmost view in the current view hierarchy.</p>
8609 *
8610 * @return the topmost view containing this view
8611 */
8612 public View getRootView() {
8613 if (mAttachInfo != null) {
8614 final View v = mAttachInfo.mRootView;
8615 if (v != null) {
8616 return v;
8617 }
8618 }
Romain Guy8506ab42009-06-11 17:35:47 -07008619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008620 View parent = this;
8621
8622 while (parent.mParent != null && parent.mParent instanceof View) {
8623 parent = (View) parent.mParent;
8624 }
8625
8626 return parent;
8627 }
8628
8629 /**
8630 * <p>Computes the coordinates of this view on the screen. The argument
8631 * must be an array of two integers. After the method returns, the array
8632 * contains the x and y location in that order.</p>
8633 *
8634 * @param location an array of two integers in which to hold the coordinates
8635 */
8636 public void getLocationOnScreen(int[] location) {
8637 getLocationInWindow(location);
8638
8639 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07008640 if (info != null) {
8641 location[0] += info.mWindowLeft;
8642 location[1] += info.mWindowTop;
8643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644 }
8645
8646 /**
8647 * <p>Computes the coordinates of this view in its window. The argument
8648 * must be an array of two integers. After the method returns, the array
8649 * contains the x and y location in that order.</p>
8650 *
8651 * @param location an array of two integers in which to hold the coordinates
8652 */
8653 public void getLocationInWindow(int[] location) {
8654 if (location == null || location.length < 2) {
8655 throw new IllegalArgumentException("location must be an array of "
8656 + "two integers");
8657 }
8658
8659 location[0] = mLeft;
8660 location[1] = mTop;
8661
8662 ViewParent viewParent = mParent;
8663 while (viewParent instanceof View) {
8664 final View view = (View)viewParent;
8665 location[0] += view.mLeft - view.mScrollX;
8666 location[1] += view.mTop - view.mScrollY;
8667 viewParent = view.mParent;
8668 }
Romain Guy8506ab42009-06-11 17:35:47 -07008669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008670 if (viewParent instanceof ViewRoot) {
8671 // *cough*
8672 final ViewRoot vr = (ViewRoot)viewParent;
8673 location[1] -= vr.mCurScrollY;
8674 }
8675 }
8676
8677 /**
8678 * {@hide}
8679 * @param id the id of the view to be found
8680 * @return the view of the specified id, null if cannot be found
8681 */
8682 protected View findViewTraversal(int id) {
8683 if (id == mID) {
8684 return this;
8685 }
8686 return null;
8687 }
8688
8689 /**
8690 * {@hide}
8691 * @param tag the tag of the view to be found
8692 * @return the view of specified tag, null if cannot be found
8693 */
8694 protected View findViewWithTagTraversal(Object tag) {
8695 if (tag != null && tag.equals(mTag)) {
8696 return this;
8697 }
8698 return null;
8699 }
8700
8701 /**
8702 * Look for a child view with the given id. If this view has the given
8703 * id, return this view.
8704 *
8705 * @param id The id to search for.
8706 * @return The view that has the given id in the hierarchy or null
8707 */
8708 public final View findViewById(int id) {
8709 if (id < 0) {
8710 return null;
8711 }
8712 return findViewTraversal(id);
8713 }
8714
8715 /**
8716 * Look for a child view with the given tag. If this view has the given
8717 * tag, return this view.
8718 *
8719 * @param tag The tag to search for, using "tag.equals(getTag())".
8720 * @return The View that has the given tag in the hierarchy or null
8721 */
8722 public final View findViewWithTag(Object tag) {
8723 if (tag == null) {
8724 return null;
8725 }
8726 return findViewWithTagTraversal(tag);
8727 }
8728
8729 /**
8730 * Sets the identifier for this view. The identifier does not have to be
8731 * unique in this view's hierarchy. The identifier should be a positive
8732 * number.
8733 *
8734 * @see #NO_ID
8735 * @see #getId
8736 * @see #findViewById
8737 *
8738 * @param id a number used to identify the view
8739 *
8740 * @attr ref android.R.styleable#View_id
8741 */
8742 public void setId(int id) {
8743 mID = id;
8744 }
8745
8746 /**
8747 * {@hide}
8748 *
8749 * @param isRoot true if the view belongs to the root namespace, false
8750 * otherwise
8751 */
8752 public void setIsRootNamespace(boolean isRoot) {
8753 if (isRoot) {
8754 mPrivateFlags |= IS_ROOT_NAMESPACE;
8755 } else {
8756 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
8757 }
8758 }
8759
8760 /**
8761 * {@hide}
8762 *
8763 * @return true if the view belongs to the root namespace, false otherwise
8764 */
8765 public boolean isRootNamespace() {
8766 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
8767 }
8768
8769 /**
8770 * Returns this view's identifier.
8771 *
8772 * @return a positive integer used to identify the view or {@link #NO_ID}
8773 * if the view has no ID
8774 *
8775 * @see #setId
8776 * @see #findViewById
8777 * @attr ref android.R.styleable#View_id
8778 */
8779 @ViewDebug.CapturedViewProperty
8780 public int getId() {
8781 return mID;
8782 }
8783
8784 /**
8785 * Returns this view's tag.
8786 *
8787 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07008788 *
8789 * @see #setTag(Object)
8790 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008791 */
8792 @ViewDebug.ExportedProperty
8793 public Object getTag() {
8794 return mTag;
8795 }
8796
8797 /**
8798 * Sets the tag associated with this view. A tag can be used to mark
8799 * a view in its hierarchy and does not have to be unique within the
8800 * hierarchy. Tags can also be used to store data within a view without
8801 * resorting to another data structure.
8802 *
8803 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07008804 *
8805 * @see #getTag()
8806 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008807 */
8808 public void setTag(final Object tag) {
8809 mTag = tag;
8810 }
8811
8812 /**
Romain Guyd90a3312009-05-06 14:54:28 -07008813 * Returns the tag associated with this view and the specified key.
8814 *
8815 * @param key The key identifying the tag
8816 *
8817 * @return the Object stored in this view as a tag
8818 *
8819 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07008820 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07008821 */
8822 public Object getTag(int key) {
8823 SparseArray<Object> tags = null;
8824 synchronized (sTagsLock) {
8825 if (sTags != null) {
8826 tags = sTags.get(this);
8827 }
8828 }
8829
8830 if (tags != null) return tags.get(key);
8831 return null;
8832 }
8833
8834 /**
8835 * Sets a tag associated with this view and a key. A tag can be used
8836 * to mark a view in its hierarchy and does not have to be unique within
8837 * the hierarchy. Tags can also be used to store data within a view
8838 * without resorting to another data structure.
8839 *
8840 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07008841 * application to ensure it is unique (see the <a
8842 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
8843 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07008844 * the Android framework or not associated with any package will cause
8845 * an {@link IllegalArgumentException} to be thrown.
8846 *
8847 * @param key The key identifying the tag
8848 * @param tag An Object to tag the view with
8849 *
8850 * @throws IllegalArgumentException If they specified key is not valid
8851 *
8852 * @see #setTag(Object)
8853 * @see #getTag(int)
8854 */
8855 public void setTag(int key, final Object tag) {
8856 // If the package id is 0x00 or 0x01, it's either an undefined package
8857 // or a framework id
8858 if ((key >>> 24) < 2) {
8859 throw new IllegalArgumentException("The key must be an application-specific "
8860 + "resource id.");
8861 }
8862
8863 setTagInternal(this, key, tag);
8864 }
8865
8866 /**
8867 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
8868 * framework id.
8869 *
8870 * @hide
8871 */
8872 public void setTagInternal(int key, Object tag) {
8873 if ((key >>> 24) != 0x1) {
8874 throw new IllegalArgumentException("The key must be a framework-specific "
8875 + "resource id.");
8876 }
8877
Romain Guy8506ab42009-06-11 17:35:47 -07008878 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07008879 }
8880
8881 private static void setTagInternal(View view, int key, Object tag) {
8882 SparseArray<Object> tags = null;
8883 synchronized (sTagsLock) {
8884 if (sTags == null) {
8885 sTags = new WeakHashMap<View, SparseArray<Object>>();
8886 } else {
8887 tags = sTags.get(view);
8888 }
8889 }
8890
8891 if (tags == null) {
8892 tags = new SparseArray<Object>(2);
8893 synchronized (sTagsLock) {
8894 sTags.put(view, tags);
8895 }
8896 }
8897
8898 tags.put(key, tag);
8899 }
8900
8901 /**
Romain Guy13922e02009-05-12 17:56:14 -07008902 * @param consistency The type of consistency. See ViewDebug for more information.
8903 *
8904 * @hide
8905 */
8906 protected boolean dispatchConsistencyCheck(int consistency) {
8907 return onConsistencyCheck(consistency);
8908 }
8909
8910 /**
8911 * Method that subclasses should implement to check their consistency. The type of
8912 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07008913 *
Romain Guy13922e02009-05-12 17:56:14 -07008914 * @param consistency The type of consistency. See ViewDebug for more information.
8915 *
8916 * @throws IllegalStateException if the view is in an inconsistent state.
8917 *
8918 * @hide
8919 */
8920 protected boolean onConsistencyCheck(int consistency) {
8921 boolean result = true;
8922
8923 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
8924 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
8925
8926 if (checkLayout) {
8927 if (getParent() == null) {
8928 result = false;
8929 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
8930 "View " + this + " does not have a parent.");
8931 }
8932
8933 if (mAttachInfo == null) {
8934 result = false;
8935 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
8936 "View " + this + " is not attached to a window.");
8937 }
8938 }
8939
8940 if (checkDrawing) {
8941 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
8942 // from their draw() method
8943
8944 if ((mPrivateFlags & DRAWN) != DRAWN &&
8945 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
8946 result = false;
8947 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
8948 "View " + this + " was invalidated but its drawing cache is valid.");
8949 }
8950 }
8951
8952 return result;
8953 }
8954
8955 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008956 * Prints information about this view in the log output, with the tag
8957 * {@link #VIEW_LOG_TAG}.
8958 *
8959 * @hide
8960 */
8961 public void debug() {
8962 debug(0);
8963 }
8964
8965 /**
8966 * Prints information about this view in the log output, with the tag
8967 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
8968 * indentation defined by the <code>depth</code>.
8969 *
8970 * @param depth the indentation level
8971 *
8972 * @hide
8973 */
8974 protected void debug(int depth) {
8975 String output = debugIndent(depth - 1);
8976
8977 output += "+ " + this;
8978 int id = getId();
8979 if (id != -1) {
8980 output += " (id=" + id + ")";
8981 }
8982 Object tag = getTag();
8983 if (tag != null) {
8984 output += " (tag=" + tag + ")";
8985 }
8986 Log.d(VIEW_LOG_TAG, output);
8987
8988 if ((mPrivateFlags & FOCUSED) != 0) {
8989 output = debugIndent(depth) + " FOCUSED";
8990 Log.d(VIEW_LOG_TAG, output);
8991 }
8992
8993 output = debugIndent(depth);
8994 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
8995 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
8996 + "} ";
8997 Log.d(VIEW_LOG_TAG, output);
8998
8999 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
9000 || mPaddingBottom != 0) {
9001 output = debugIndent(depth);
9002 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
9003 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
9004 Log.d(VIEW_LOG_TAG, output);
9005 }
9006
9007 output = debugIndent(depth);
9008 output += "mMeasureWidth=" + mMeasuredWidth +
9009 " mMeasureHeight=" + mMeasuredHeight;
9010 Log.d(VIEW_LOG_TAG, output);
9011
9012 output = debugIndent(depth);
9013 if (mLayoutParams == null) {
9014 output += "BAD! no layout params";
9015 } else {
9016 output = mLayoutParams.debug(output);
9017 }
9018 Log.d(VIEW_LOG_TAG, output);
9019
9020 output = debugIndent(depth);
9021 output += "flags={";
9022 output += View.printFlags(mViewFlags);
9023 output += "}";
9024 Log.d(VIEW_LOG_TAG, output);
9025
9026 output = debugIndent(depth);
9027 output += "privateFlags={";
9028 output += View.printPrivateFlags(mPrivateFlags);
9029 output += "}";
9030 Log.d(VIEW_LOG_TAG, output);
9031 }
9032
9033 /**
9034 * Creates an string of whitespaces used for indentation.
9035 *
9036 * @param depth the indentation level
9037 * @return a String containing (depth * 2 + 3) * 2 white spaces
9038 *
9039 * @hide
9040 */
9041 protected static String debugIndent(int depth) {
9042 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
9043 for (int i = 0; i < (depth * 2) + 3; i++) {
9044 spaces.append(' ').append(' ');
9045 }
9046 return spaces.toString();
9047 }
9048
9049 /**
9050 * <p>Return the offset of the widget's text baseline from the widget's top
9051 * boundary. If this widget does not support baseline alignment, this
9052 * method returns -1. </p>
9053 *
9054 * @return the offset of the baseline within the widget's bounds or -1
9055 * if baseline alignment is not supported
9056 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07009057 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009058 public int getBaseline() {
9059 return -1;
9060 }
9061
9062 /**
9063 * Call this when something has changed which has invalidated the
9064 * layout of this view. This will schedule a layout pass of the view
9065 * tree.
9066 */
9067 public void requestLayout() {
9068 if (ViewDebug.TRACE_HIERARCHY) {
9069 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
9070 }
9071
9072 mPrivateFlags |= FORCE_LAYOUT;
9073
9074 if (mParent != null && !mParent.isLayoutRequested()) {
9075 mParent.requestLayout();
9076 }
9077 }
9078
9079 /**
9080 * Forces this view to be laid out during the next layout pass.
9081 * This method does not call requestLayout() or forceLayout()
9082 * on the parent.
9083 */
9084 public void forceLayout() {
9085 mPrivateFlags |= FORCE_LAYOUT;
9086 }
9087
9088 /**
9089 * <p>
9090 * This is called to find out how big a view should be. The parent
9091 * supplies constraint information in the width and height parameters.
9092 * </p>
9093 *
9094 * <p>
9095 * The actual mesurement work of a view is performed in
9096 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
9097 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
9098 * </p>
9099 *
9100 *
9101 * @param widthMeasureSpec Horizontal space requirements as imposed by the
9102 * parent
9103 * @param heightMeasureSpec Vertical space requirements as imposed by the
9104 * parent
9105 *
9106 * @see #onMeasure(int, int)
9107 */
9108 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
9109 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
9110 widthMeasureSpec != mOldWidthMeasureSpec ||
9111 heightMeasureSpec != mOldHeightMeasureSpec) {
9112
9113 // first clears the measured dimension flag
9114 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
9115
9116 if (ViewDebug.TRACE_HIERARCHY) {
9117 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
9118 }
9119
9120 // measure ourselves, this should set the measured dimension flag back
9121 onMeasure(widthMeasureSpec, heightMeasureSpec);
9122
9123 // flag not set, setMeasuredDimension() was not invoked, we raise
9124 // an exception to warn the developer
9125 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
9126 throw new IllegalStateException("onMeasure() did not set the"
9127 + " measured dimension by calling"
9128 + " setMeasuredDimension()");
9129 }
9130
9131 mPrivateFlags |= LAYOUT_REQUIRED;
9132 }
9133
9134 mOldWidthMeasureSpec = widthMeasureSpec;
9135 mOldHeightMeasureSpec = heightMeasureSpec;
9136 }
9137
9138 /**
9139 * <p>
9140 * Measure the view and its content to determine the measured width and the
9141 * measured height. This method is invoked by {@link #measure(int, int)} and
9142 * should be overriden by subclasses to provide accurate and efficient
9143 * measurement of their contents.
9144 * </p>
9145 *
9146 * <p>
9147 * <strong>CONTRACT:</strong> When overriding this method, you
9148 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
9149 * measured width and height of this view. Failure to do so will trigger an
9150 * <code>IllegalStateException</code>, thrown by
9151 * {@link #measure(int, int)}. Calling the superclass'
9152 * {@link #onMeasure(int, int)} is a valid use.
9153 * </p>
9154 *
9155 * <p>
9156 * The base class implementation of measure defaults to the background size,
9157 * unless a larger size is allowed by the MeasureSpec. Subclasses should
9158 * override {@link #onMeasure(int, int)} to provide better measurements of
9159 * their content.
9160 * </p>
9161 *
9162 * <p>
9163 * If this method is overridden, it is the subclass's responsibility to make
9164 * sure the measured height and width are at least the view's minimum height
9165 * and width ({@link #getSuggestedMinimumHeight()} and
9166 * {@link #getSuggestedMinimumWidth()}).
9167 * </p>
9168 *
9169 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
9170 * The requirements are encoded with
9171 * {@link android.view.View.MeasureSpec}.
9172 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
9173 * The requirements are encoded with
9174 * {@link android.view.View.MeasureSpec}.
9175 *
9176 * @see #getMeasuredWidth()
9177 * @see #getMeasuredHeight()
9178 * @see #setMeasuredDimension(int, int)
9179 * @see #getSuggestedMinimumHeight()
9180 * @see #getSuggestedMinimumWidth()
9181 * @see android.view.View.MeasureSpec#getMode(int)
9182 * @see android.view.View.MeasureSpec#getSize(int)
9183 */
9184 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
9185 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
9186 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
9187 }
9188
9189 /**
9190 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
9191 * measured width and measured height. Failing to do so will trigger an
9192 * exception at measurement time.</p>
9193 *
9194 * @param measuredWidth the measured width of this view
9195 * @param measuredHeight the measured height of this view
9196 */
9197 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
9198 mMeasuredWidth = measuredWidth;
9199 mMeasuredHeight = measuredHeight;
9200
9201 mPrivateFlags |= MEASURED_DIMENSION_SET;
9202 }
9203
9204 /**
9205 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
9206 * Will take the desired size, unless a different size is imposed by the constraints.
9207 *
9208 * @param size How big the view wants to be
9209 * @param measureSpec Constraints imposed by the parent
9210 * @return The size this view should be.
9211 */
9212 public static int resolveSize(int size, int measureSpec) {
9213 int result = size;
9214 int specMode = MeasureSpec.getMode(measureSpec);
9215 int specSize = MeasureSpec.getSize(measureSpec);
9216 switch (specMode) {
9217 case MeasureSpec.UNSPECIFIED:
9218 result = size;
9219 break;
9220 case MeasureSpec.AT_MOST:
9221 result = Math.min(size, specSize);
9222 break;
9223 case MeasureSpec.EXACTLY:
9224 result = specSize;
9225 break;
9226 }
9227 return result;
9228 }
9229
9230 /**
9231 * Utility to return a default size. Uses the supplied size if the
9232 * MeasureSpec imposed no contraints. Will get larger if allowed
9233 * by the MeasureSpec.
9234 *
9235 * @param size Default size for this view
9236 * @param measureSpec Constraints imposed by the parent
9237 * @return The size this view should be.
9238 */
9239 public static int getDefaultSize(int size, int measureSpec) {
9240 int result = size;
9241 int specMode = MeasureSpec.getMode(measureSpec);
9242 int specSize = MeasureSpec.getSize(measureSpec);
9243
9244 switch (specMode) {
9245 case MeasureSpec.UNSPECIFIED:
9246 result = size;
9247 break;
9248 case MeasureSpec.AT_MOST:
9249 case MeasureSpec.EXACTLY:
9250 result = specSize;
9251 break;
9252 }
9253 return result;
9254 }
9255
9256 /**
9257 * Returns the suggested minimum height that the view should use. This
9258 * returns the maximum of the view's minimum height
9259 * and the background's minimum height
9260 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
9261 * <p>
9262 * When being used in {@link #onMeasure(int, int)}, the caller should still
9263 * ensure the returned height is within the requirements of the parent.
9264 *
9265 * @return The suggested minimum height of the view.
9266 */
9267 protected int getSuggestedMinimumHeight() {
9268 int suggestedMinHeight = mMinHeight;
9269
9270 if (mBGDrawable != null) {
9271 final int bgMinHeight = mBGDrawable.getMinimumHeight();
9272 if (suggestedMinHeight < bgMinHeight) {
9273 suggestedMinHeight = bgMinHeight;
9274 }
9275 }
9276
9277 return suggestedMinHeight;
9278 }
9279
9280 /**
9281 * Returns the suggested minimum width that the view should use. This
9282 * returns the maximum of the view's minimum width)
9283 * and the background's minimum width
9284 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
9285 * <p>
9286 * When being used in {@link #onMeasure(int, int)}, the caller should still
9287 * ensure the returned width is within the requirements of the parent.
9288 *
9289 * @return The suggested minimum width of the view.
9290 */
9291 protected int getSuggestedMinimumWidth() {
9292 int suggestedMinWidth = mMinWidth;
9293
9294 if (mBGDrawable != null) {
9295 final int bgMinWidth = mBGDrawable.getMinimumWidth();
9296 if (suggestedMinWidth < bgMinWidth) {
9297 suggestedMinWidth = bgMinWidth;
9298 }
9299 }
9300
9301 return suggestedMinWidth;
9302 }
9303
9304 /**
9305 * Sets the minimum height of the view. It is not guaranteed the view will
9306 * be able to achieve this minimum height (for example, if its parent layout
9307 * constrains it with less available height).
9308 *
9309 * @param minHeight The minimum height the view will try to be.
9310 */
9311 public void setMinimumHeight(int minHeight) {
9312 mMinHeight = minHeight;
9313 }
9314
9315 /**
9316 * Sets the minimum width of the view. It is not guaranteed the view will
9317 * be able to achieve this minimum width (for example, if its parent layout
9318 * constrains it with less available width).
9319 *
9320 * @param minWidth The minimum width the view will try to be.
9321 */
9322 public void setMinimumWidth(int minWidth) {
9323 mMinWidth = minWidth;
9324 }
9325
9326 /**
9327 * Get the animation currently associated with this view.
9328 *
9329 * @return The animation that is currently playing or
9330 * scheduled to play for this view.
9331 */
9332 public Animation getAnimation() {
9333 return mCurrentAnimation;
9334 }
9335
9336 /**
9337 * Start the specified animation now.
9338 *
9339 * @param animation the animation to start now
9340 */
9341 public void startAnimation(Animation animation) {
9342 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
9343 setAnimation(animation);
9344 invalidate();
9345 }
9346
9347 /**
9348 * Cancels any animations for this view.
9349 */
9350 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08009351 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08009352 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08009353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009354 mCurrentAnimation = null;
9355 }
9356
9357 /**
9358 * Sets the next animation to play for this view.
9359 * If you want the animation to play immediately, use
9360 * startAnimation. This method provides allows fine-grained
9361 * control over the start time and invalidation, but you
9362 * must make sure that 1) the animation has a start time set, and
9363 * 2) the view will be invalidated when the animation is supposed to
9364 * start.
9365 *
9366 * @param animation The next animation, or null.
9367 */
9368 public void setAnimation(Animation animation) {
9369 mCurrentAnimation = animation;
9370 if (animation != null) {
9371 animation.reset();
9372 }
9373 }
9374
9375 /**
9376 * Invoked by a parent ViewGroup to notify the start of the animation
9377 * currently associated with this view. If you override this method,
9378 * always call super.onAnimationStart();
9379 *
9380 * @see #setAnimation(android.view.animation.Animation)
9381 * @see #getAnimation()
9382 */
9383 protected void onAnimationStart() {
9384 mPrivateFlags |= ANIMATION_STARTED;
9385 }
9386
9387 /**
9388 * Invoked by a parent ViewGroup to notify the end of the animation
9389 * currently associated with this view. If you override this method,
9390 * always call super.onAnimationEnd();
9391 *
9392 * @see #setAnimation(android.view.animation.Animation)
9393 * @see #getAnimation()
9394 */
9395 protected void onAnimationEnd() {
9396 mPrivateFlags &= ~ANIMATION_STARTED;
9397 }
9398
9399 /**
9400 * Invoked if there is a Transform that involves alpha. Subclass that can
9401 * draw themselves with the specified alpha should return true, and then
9402 * respect that alpha when their onDraw() is called. If this returns false
9403 * then the view may be redirected to draw into an offscreen buffer to
9404 * fulfill the request, which will look fine, but may be slower than if the
9405 * subclass handles it internally. The default implementation returns false.
9406 *
9407 * @param alpha The alpha (0..255) to apply to the view's drawing
9408 * @return true if the view can draw with the specified alpha.
9409 */
9410 protected boolean onSetAlpha(int alpha) {
9411 return false;
9412 }
9413
9414 /**
9415 * This is used by the RootView to perform an optimization when
9416 * the view hierarchy contains one or several SurfaceView.
9417 * SurfaceView is always considered transparent, but its children are not,
9418 * therefore all View objects remove themselves from the global transparent
9419 * region (passed as a parameter to this function).
9420 *
9421 * @param region The transparent region for this ViewRoot (window).
9422 *
9423 * @return Returns true if the effective visibility of the view at this
9424 * point is opaque, regardless of the transparent region; returns false
9425 * if it is possible for underlying windows to be seen behind the view.
9426 *
9427 * {@hide}
9428 */
9429 public boolean gatherTransparentRegion(Region region) {
9430 final AttachInfo attachInfo = mAttachInfo;
9431 if (region != null && attachInfo != null) {
9432 final int pflags = mPrivateFlags;
9433 if ((pflags & SKIP_DRAW) == 0) {
9434 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
9435 // remove it from the transparent region.
9436 final int[] location = attachInfo.mTransparentLocation;
9437 getLocationInWindow(location);
9438 region.op(location[0], location[1], location[0] + mRight - mLeft,
9439 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
9440 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
9441 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
9442 // exists, so we remove the background drawable's non-transparent
9443 // parts from this transparent region.
9444 applyDrawableToTransparentRegion(mBGDrawable, region);
9445 }
9446 }
9447 return true;
9448 }
9449
9450 /**
9451 * Play a sound effect for this view.
9452 *
9453 * <p>The framework will play sound effects for some built in actions, such as
9454 * clicking, but you may wish to play these effects in your widget,
9455 * for instance, for internal navigation.
9456 *
9457 * <p>The sound effect will only be played if sound effects are enabled by the user, and
9458 * {@link #isSoundEffectsEnabled()} is true.
9459 *
9460 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
9461 */
9462 public void playSoundEffect(int soundConstant) {
9463 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
9464 return;
9465 }
9466 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
9467 }
9468
9469 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009470 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009471 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009472 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009473 *
9474 * <p>The framework will provide haptic feedback for some built in actions,
9475 * such as long presses, but you may wish to provide feedback for your
9476 * own widget.
9477 *
9478 * <p>The feedback will only be performed if
9479 * {@link #isHapticFeedbackEnabled()} is true.
9480 *
9481 * @param feedbackConstant One of the constants defined in
9482 * {@link HapticFeedbackConstants}
9483 */
9484 public boolean performHapticFeedback(int feedbackConstant) {
9485 return performHapticFeedback(feedbackConstant, 0);
9486 }
9487
9488 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009489 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009490 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009491 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009492 *
9493 * @param feedbackConstant One of the constants defined in
9494 * {@link HapticFeedbackConstants}
9495 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
9496 */
9497 public boolean performHapticFeedback(int feedbackConstant, int flags) {
9498 if (mAttachInfo == null) {
9499 return false;
9500 }
Romain Guy812ccbe2010-06-01 14:07:24 -07009501 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009502 && !isHapticFeedbackEnabled()) {
9503 return false;
9504 }
Romain Guy812ccbe2010-06-01 14:07:24 -07009505 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
9506 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009507 }
9508
9509 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -07009510 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
9511 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -07009512 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -07009513 */
9514 public void onCloseSystemDialogs(String reason) {
9515 }
9516
9517 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009518 * Given a Drawable whose bounds have been set to draw into this view,
9519 * update a Region being computed for {@link #gatherTransparentRegion} so
9520 * that any non-transparent parts of the Drawable are removed from the
9521 * given transparent region.
9522 *
9523 * @param dr The Drawable whose transparency is to be applied to the region.
9524 * @param region A Region holding the current transparency information,
9525 * where any parts of the region that are set are considered to be
9526 * transparent. On return, this region will be modified to have the
9527 * transparency information reduced by the corresponding parts of the
9528 * Drawable that are not transparent.
9529 * {@hide}
9530 */
9531 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
9532 if (DBG) {
9533 Log.i("View", "Getting transparent region for: " + this);
9534 }
9535 final Region r = dr.getTransparentRegion();
9536 final Rect db = dr.getBounds();
9537 final AttachInfo attachInfo = mAttachInfo;
9538 if (r != null && attachInfo != null) {
9539 final int w = getRight()-getLeft();
9540 final int h = getBottom()-getTop();
9541 if (db.left > 0) {
9542 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
9543 r.op(0, 0, db.left, h, Region.Op.UNION);
9544 }
9545 if (db.right < w) {
9546 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
9547 r.op(db.right, 0, w, h, Region.Op.UNION);
9548 }
9549 if (db.top > 0) {
9550 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
9551 r.op(0, 0, w, db.top, Region.Op.UNION);
9552 }
9553 if (db.bottom < h) {
9554 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
9555 r.op(0, db.bottom, w, h, Region.Op.UNION);
9556 }
9557 final int[] location = attachInfo.mTransparentLocation;
9558 getLocationInWindow(location);
9559 r.translate(location[0], location[1]);
9560 region.op(r, Region.Op.INTERSECT);
9561 } else {
9562 region.op(db, Region.Op.DIFFERENCE);
9563 }
9564 }
9565
Adam Powelle14579b2009-12-16 18:39:52 -08009566 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009567 mHasPerformedLongPress = false;
9568
9569 if (mPendingCheckForLongPress == null) {
9570 mPendingCheckForLongPress = new CheckForLongPress();
9571 }
9572 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -08009573 postDelayed(mPendingCheckForLongPress,
9574 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009575 }
9576
Romain Guy812ccbe2010-06-01 14:07:24 -07009577 private static int[] stateSetUnion(final int[] stateSet1, final int[] stateSet2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009578 final int stateSet1Length = stateSet1.length;
9579 final int stateSet2Length = stateSet2.length;
9580 final int[] newSet = new int[stateSet1Length + stateSet2Length];
9581 int k = 0;
9582 int i = 0;
9583 int j = 0;
9584 // This is a merge of the two input state sets and assumes that the
9585 // input sets are sorted by the order imposed by ViewDrawableStates.
9586 for (int viewState : R.styleable.ViewDrawableStates) {
9587 if (i < stateSet1Length && stateSet1[i] == viewState) {
9588 newSet[k++] = viewState;
9589 i++;
9590 } else if (j < stateSet2Length && stateSet2[j] == viewState) {
9591 newSet[k++] = viewState;
9592 j++;
9593 }
9594 if (k > 1) {
9595 assert(newSet[k - 1] > newSet[k - 2]);
9596 }
9597 }
9598 return newSet;
9599 }
9600
9601 /**
9602 * Inflate a view from an XML resource. This convenience method wraps the {@link
9603 * LayoutInflater} class, which provides a full range of options for view inflation.
9604 *
9605 * @param context The Context object for your activity or application.
9606 * @param resource The resource ID to inflate
9607 * @param root A view group that will be the parent. Used to properly inflate the
9608 * layout_* parameters.
9609 * @see LayoutInflater
9610 */
9611 public static View inflate(Context context, int resource, ViewGroup root) {
9612 LayoutInflater factory = LayoutInflater.from(context);
9613 return factory.inflate(resource, root);
9614 }
Romain Guy33e72ae2010-07-17 12:40:29 -07009615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009616 /**
9617 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
9618 * Each MeasureSpec represents a requirement for either the width or the height.
9619 * A MeasureSpec is comprised of a size and a mode. There are three possible
9620 * modes:
9621 * <dl>
9622 * <dt>UNSPECIFIED</dt>
9623 * <dd>
9624 * The parent has not imposed any constraint on the child. It can be whatever size
9625 * it wants.
9626 * </dd>
9627 *
9628 * <dt>EXACTLY</dt>
9629 * <dd>
9630 * The parent has determined an exact size for the child. The child is going to be
9631 * given those bounds regardless of how big it wants to be.
9632 * </dd>
9633 *
9634 * <dt>AT_MOST</dt>
9635 * <dd>
9636 * The child can be as large as it wants up to the specified size.
9637 * </dd>
9638 * </dl>
9639 *
9640 * MeasureSpecs are implemented as ints to reduce object allocation. This class
9641 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
9642 */
9643 public static class MeasureSpec {
9644 private static final int MODE_SHIFT = 30;
9645 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
9646
9647 /**
9648 * Measure specification mode: The parent has not imposed any constraint
9649 * on the child. It can be whatever size it wants.
9650 */
9651 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
9652
9653 /**
9654 * Measure specification mode: The parent has determined an exact size
9655 * for the child. The child is going to be given those bounds regardless
9656 * of how big it wants to be.
9657 */
9658 public static final int EXACTLY = 1 << MODE_SHIFT;
9659
9660 /**
9661 * Measure specification mode: The child can be as large as it wants up
9662 * to the specified size.
9663 */
9664 public static final int AT_MOST = 2 << MODE_SHIFT;
9665
9666 /**
9667 * Creates a measure specification based on the supplied size and mode.
9668 *
9669 * The mode must always be one of the following:
9670 * <ul>
9671 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
9672 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
9673 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
9674 * </ul>
9675 *
9676 * @param size the size of the measure specification
9677 * @param mode the mode of the measure specification
9678 * @return the measure specification based on size and mode
9679 */
9680 public static int makeMeasureSpec(int size, int mode) {
9681 return size + mode;
9682 }
9683
9684 /**
9685 * Extracts the mode from the supplied measure specification.
9686 *
9687 * @param measureSpec the measure specification to extract the mode from
9688 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
9689 * {@link android.view.View.MeasureSpec#AT_MOST} or
9690 * {@link android.view.View.MeasureSpec#EXACTLY}
9691 */
9692 public static int getMode(int measureSpec) {
9693 return (measureSpec & MODE_MASK);
9694 }
9695
9696 /**
9697 * Extracts the size from the supplied measure specification.
9698 *
9699 * @param measureSpec the measure specification to extract the size from
9700 * @return the size in pixels defined in the supplied measure specification
9701 */
9702 public static int getSize(int measureSpec) {
9703 return (measureSpec & ~MODE_MASK);
9704 }
9705
9706 /**
9707 * Returns a String representation of the specified measure
9708 * specification.
9709 *
9710 * @param measureSpec the measure specification to convert to a String
9711 * @return a String with the following format: "MeasureSpec: MODE SIZE"
9712 */
9713 public static String toString(int measureSpec) {
9714 int mode = getMode(measureSpec);
9715 int size = getSize(measureSpec);
9716
9717 StringBuilder sb = new StringBuilder("MeasureSpec: ");
9718
9719 if (mode == UNSPECIFIED)
9720 sb.append("UNSPECIFIED ");
9721 else if (mode == EXACTLY)
9722 sb.append("EXACTLY ");
9723 else if (mode == AT_MOST)
9724 sb.append("AT_MOST ");
9725 else
9726 sb.append(mode).append(" ");
9727
9728 sb.append(size);
9729 return sb.toString();
9730 }
9731 }
9732
9733 class CheckForLongPress implements Runnable {
9734
9735 private int mOriginalWindowAttachCount;
9736
9737 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -07009738 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009739 && mOriginalWindowAttachCount == mWindowAttachCount) {
9740 if (performLongClick()) {
9741 mHasPerformedLongPress = true;
9742 }
9743 }
9744 }
9745
9746 public void rememberWindowAttachCount() {
9747 mOriginalWindowAttachCount = mWindowAttachCount;
9748 }
9749 }
Adam Powelle14579b2009-12-16 18:39:52 -08009750
9751 private final class CheckForTap implements Runnable {
9752 public void run() {
9753 mPrivateFlags &= ~PREPRESSED;
9754 mPrivateFlags |= PRESSED;
9755 refreshDrawableState();
9756 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
9757 postCheckForLongClick(ViewConfiguration.getTapTimeout());
9758 }
9759 }
9760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009761
Adam Powella35d7682010-03-12 14:48:13 -08009762 private final class PerformClick implements Runnable {
9763 public void run() {
9764 performClick();
9765 }
9766 }
9767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009768 /**
9769 * Interface definition for a callback to be invoked when a key event is
9770 * dispatched to this view. The callback will be invoked before the key
9771 * event is given to the view.
9772 */
9773 public interface OnKeyListener {
9774 /**
9775 * Called when a key is dispatched to a view. This allows listeners to
9776 * get a chance to respond before the target view.
9777 *
9778 * @param v The view the key has been dispatched to.
9779 * @param keyCode The code for the physical key that was pressed
9780 * @param event The KeyEvent object containing full information about
9781 * the event.
9782 * @return True if the listener has consumed the event, false otherwise.
9783 */
9784 boolean onKey(View v, int keyCode, KeyEvent event);
9785 }
9786
9787 /**
9788 * Interface definition for a callback to be invoked when a touch event is
9789 * dispatched to this view. The callback will be invoked before the touch
9790 * event is given to the view.
9791 */
9792 public interface OnTouchListener {
9793 /**
9794 * Called when a touch event is dispatched to a view. This allows listeners to
9795 * get a chance to respond before the target view.
9796 *
9797 * @param v The view the touch event has been dispatched to.
9798 * @param event The MotionEvent object containing full information about
9799 * the event.
9800 * @return True if the listener has consumed the event, false otherwise.
9801 */
9802 boolean onTouch(View v, MotionEvent event);
9803 }
9804
9805 /**
9806 * Interface definition for a callback to be invoked when a view has been clicked and held.
9807 */
9808 public interface OnLongClickListener {
9809 /**
9810 * Called when a view has been clicked and held.
9811 *
9812 * @param v The view that was clicked and held.
9813 *
9814 * return True if the callback consumed the long click, false otherwise
9815 */
9816 boolean onLongClick(View v);
9817 }
9818
9819 /**
9820 * Interface definition for a callback to be invoked when the focus state of
9821 * a view changed.
9822 */
9823 public interface OnFocusChangeListener {
9824 /**
9825 * Called when the focus state of a view has changed.
9826 *
9827 * @param v The view whose state has changed.
9828 * @param hasFocus The new focus state of v.
9829 */
9830 void onFocusChange(View v, boolean hasFocus);
9831 }
9832
9833 /**
9834 * Interface definition for a callback to be invoked when a view is clicked.
9835 */
9836 public interface OnClickListener {
9837 /**
9838 * Called when a view has been clicked.
9839 *
9840 * @param v The view that was clicked.
9841 */
9842 void onClick(View v);
9843 }
9844
9845 /**
9846 * Interface definition for a callback to be invoked when the context menu
9847 * for this view is being built.
9848 */
9849 public interface OnCreateContextMenuListener {
9850 /**
9851 * Called when the context menu for this view is being built. It is not
9852 * safe to hold onto the menu after this method returns.
9853 *
9854 * @param menu The context menu that is being built
9855 * @param v The view for which the context menu is being built
9856 * @param menuInfo Extra information about the item for which the
9857 * context menu should be shown. This information will vary
9858 * depending on the class of v.
9859 */
9860 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
9861 }
9862
9863 private final class UnsetPressedState implements Runnable {
9864 public void run() {
9865 setPressed(false);
9866 }
9867 }
9868
9869 /**
9870 * Base class for derived classes that want to save and restore their own
9871 * state in {@link android.view.View#onSaveInstanceState()}.
9872 */
9873 public static class BaseSavedState extends AbsSavedState {
9874 /**
9875 * Constructor used when reading from a parcel. Reads the state of the superclass.
9876 *
9877 * @param source
9878 */
9879 public BaseSavedState(Parcel source) {
9880 super(source);
9881 }
9882
9883 /**
9884 * Constructor called by derived classes when creating their SavedState objects
9885 *
9886 * @param superState The state of the superclass of this view
9887 */
9888 public BaseSavedState(Parcelable superState) {
9889 super(superState);
9890 }
9891
9892 public static final Parcelable.Creator<BaseSavedState> CREATOR =
9893 new Parcelable.Creator<BaseSavedState>() {
9894 public BaseSavedState createFromParcel(Parcel in) {
9895 return new BaseSavedState(in);
9896 }
9897
9898 public BaseSavedState[] newArray(int size) {
9899 return new BaseSavedState[size];
9900 }
9901 };
9902 }
9903
9904 /**
9905 * A set of information given to a view when it is attached to its parent
9906 * window.
9907 */
9908 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009909 interface Callbacks {
9910 void playSoundEffect(int effectId);
9911 boolean performHapticFeedback(int effectId, boolean always);
9912 }
9913
9914 /**
9915 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
9916 * to a Handler. This class contains the target (View) to invalidate and
9917 * the coordinates of the dirty rectangle.
9918 *
9919 * For performance purposes, this class also implements a pool of up to
9920 * POOL_LIMIT objects that get reused. This reduces memory allocations
9921 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009922 */
Romain Guyd928d682009-03-31 17:52:16 -07009923 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009924 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -07009925 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
9926 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -07009927 public InvalidateInfo newInstance() {
9928 return new InvalidateInfo();
9929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009930
Romain Guyd928d682009-03-31 17:52:16 -07009931 public void onAcquired(InvalidateInfo element) {
9932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009933
Romain Guyd928d682009-03-31 17:52:16 -07009934 public void onReleased(InvalidateInfo element) {
9935 }
9936 }, POOL_LIMIT)
9937 );
9938
9939 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009940
9941 View target;
9942
9943 int left;
9944 int top;
9945 int right;
9946 int bottom;
9947
Romain Guyd928d682009-03-31 17:52:16 -07009948 public void setNextPoolable(InvalidateInfo element) {
9949 mNext = element;
9950 }
9951
9952 public InvalidateInfo getNextPoolable() {
9953 return mNext;
9954 }
9955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009956 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -07009957 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009958 }
9959
9960 void release() {
Romain Guyd928d682009-03-31 17:52:16 -07009961 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009962 }
9963 }
9964
9965 final IWindowSession mSession;
9966
9967 final IWindow mWindow;
9968
9969 final IBinder mWindowToken;
9970
9971 final Callbacks mRootCallbacks;
9972
9973 /**
9974 * The top view of the hierarchy.
9975 */
9976 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -07009977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009978 IBinder mPanelParentWindowToken;
9979 Surface mSurface;
9980
9981 /**
Romain Guy8506ab42009-06-11 17:35:47 -07009982 * Scale factor used by the compatibility mode
9983 */
9984 float mApplicationScale;
9985
9986 /**
9987 * Indicates whether the application is in compatibility mode
9988 */
9989 boolean mScalingRequired;
9990
9991 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009992 * Left position of this view's window
9993 */
9994 int mWindowLeft;
9995
9996 /**
9997 * Top position of this view's window
9998 */
9999 int mWindowTop;
10000
10001 /**
Romain Guy35b38ce2009-10-07 13:38:55 -070010002 * Indicates whether the window is translucent/transparent
10003 */
10004 boolean mTranslucentWindow;
10005
10006 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010007 * For windows that are full-screen but using insets to layout inside
10008 * of the screen decorations, these are the current insets for the
10009 * content of the window.
10010 */
10011 final Rect mContentInsets = new Rect();
10012
10013 /**
10014 * For windows that are full-screen but using insets to layout inside
10015 * of the screen decorations, these are the current insets for the
10016 * actual visible parts of the window.
10017 */
10018 final Rect mVisibleInsets = new Rect();
10019
10020 /**
10021 * The internal insets given by this window. This value is
10022 * supplied by the client (through
10023 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
10024 * be given to the window manager when changed to be used in laying
10025 * out windows behind it.
10026 */
10027 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
10028 = new ViewTreeObserver.InternalInsetsInfo();
10029
10030 /**
10031 * All views in the window's hierarchy that serve as scroll containers,
10032 * used to determine if the window can be resized or must be panned
10033 * to adjust for a soft input area.
10034 */
10035 final ArrayList<View> mScrollContainers = new ArrayList<View>();
10036
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070010037 final KeyEvent.DispatcherState mKeyDispatchState
10038 = new KeyEvent.DispatcherState();
10039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010040 /**
10041 * Indicates whether the view's window currently has the focus.
10042 */
10043 boolean mHasWindowFocus;
10044
10045 /**
10046 * The current visibility of the window.
10047 */
10048 int mWindowVisibility;
10049
10050 /**
10051 * Indicates the time at which drawing started to occur.
10052 */
10053 long mDrawingTime;
10054
10055 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070010056 * Indicates whether or not ignoring the DIRTY_MASK flags.
10057 */
10058 boolean mIgnoreDirtyState;
10059
10060 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010061 * Indicates whether the view's window is currently in touch mode.
10062 */
10063 boolean mInTouchMode;
10064
10065 /**
10066 * Indicates that ViewRoot should trigger a global layout change
10067 * the next time it performs a traversal
10068 */
10069 boolean mRecomputeGlobalAttributes;
10070
10071 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010072 * Set during a traveral if any views want to keep the screen on.
10073 */
10074 boolean mKeepScreenOn;
10075
10076 /**
10077 * Set if the visibility of any views has changed.
10078 */
10079 boolean mViewVisibilityChanged;
10080
10081 /**
10082 * Set to true if a view has been scrolled.
10083 */
10084 boolean mViewScrollChanged;
10085
10086 /**
10087 * Global to the view hierarchy used as a temporary for dealing with
10088 * x/y points in the transparent region computations.
10089 */
10090 final int[] mTransparentLocation = new int[2];
10091
10092 /**
10093 * Global to the view hierarchy used as a temporary for dealing with
10094 * x/y points in the ViewGroup.invalidateChild implementation.
10095 */
10096 final int[] mInvalidateChildLocation = new int[2];
10097
Chet Haasec3aa3612010-06-17 08:50:37 -070010098
10099 /**
10100 * Global to the view hierarchy used as a temporary for dealing with
10101 * x/y location when view is transformed.
10102 */
10103 final float[] mTmpTransformLocation = new float[2];
10104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010105 /**
10106 * The view tree observer used to dispatch global events like
10107 * layout, pre-draw, touch mode change, etc.
10108 */
10109 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
10110
10111 /**
10112 * A Canvas used by the view hierarchy to perform bitmap caching.
10113 */
10114 Canvas mCanvas;
10115
10116 /**
10117 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
10118 * handler can be used to pump events in the UI events queue.
10119 */
10120 final Handler mHandler;
10121
10122 /**
10123 * Identifier for messages requesting the view to be invalidated.
10124 * Such messages should be sent to {@link #mHandler}.
10125 */
10126 static final int INVALIDATE_MSG = 0x1;
10127
10128 /**
10129 * Identifier for messages requesting the view to invalidate a region.
10130 * Such messages should be sent to {@link #mHandler}.
10131 */
10132 static final int INVALIDATE_RECT_MSG = 0x2;
10133
10134 /**
10135 * Temporary for use in computing invalidate rectangles while
10136 * calling up the hierarchy.
10137 */
10138 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070010139
10140 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070010141 * Temporary for use in computing hit areas with transformed views
10142 */
10143 final RectF mTmpTransformRect = new RectF();
10144
10145 /**
10146 * Temporary for use in computing invalidation areas with transformed views
10147 */
10148 final float[] mTmpTransformBounds = new float[8];
10149
10150 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070010151 * Temporary list for use in collecting focusable descendents of a view.
10152 */
10153 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
10154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010155 /**
10156 * Creates a new set of attachment information with the specified
10157 * events handler and thread.
10158 *
10159 * @param handler the events handler the view must use
10160 */
10161 AttachInfo(IWindowSession session, IWindow window,
10162 Handler handler, Callbacks effectPlayer) {
10163 mSession = session;
10164 mWindow = window;
10165 mWindowToken = window.asBinder();
10166 mHandler = handler;
10167 mRootCallbacks = effectPlayer;
10168 }
10169 }
10170
10171 /**
10172 * <p>ScrollabilityCache holds various fields used by a View when scrolling
10173 * is supported. This avoids keeping too many unused fields in most
10174 * instances of View.</p>
10175 */
Mike Cleronf116bf82009-09-27 19:14:12 -070010176 private static class ScrollabilityCache implements Runnable {
10177
10178 /**
10179 * Scrollbars are not visible
10180 */
10181 public static final int OFF = 0;
10182
10183 /**
10184 * Scrollbars are visible
10185 */
10186 public static final int ON = 1;
10187
10188 /**
10189 * Scrollbars are fading away
10190 */
10191 public static final int FADING = 2;
10192
10193 public boolean fadeScrollBars;
10194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010195 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070010196 public int scrollBarDefaultDelayBeforeFade;
10197 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010198
10199 public int scrollBarSize;
10200 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070010201 public float[] interpolatorValues;
10202 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010203
10204 public final Paint paint;
10205 public final Matrix matrix;
10206 public Shader shader;
10207
Mike Cleronf116bf82009-09-27 19:14:12 -070010208 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
10209
Romain Guy8fb95422010-08-17 18:38:51 -070010210 private final float[] mOpaque = { 255.0f };
10211 private final float[] mTransparent = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070010212
10213 /**
10214 * When fading should start. This time moves into the future every time
10215 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
10216 */
10217 public long fadeStartTime;
10218
10219
10220 /**
10221 * The current state of the scrollbars: ON, OFF, or FADING
10222 */
10223 public int state = OFF;
10224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010225 private int mLastColor;
10226
Mike Cleronf116bf82009-09-27 19:14:12 -070010227 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010228 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
10229 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070010230 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
10231 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010232
10233 paint = new Paint();
10234 matrix = new Matrix();
10235 // use use a height of 1, and then wack the matrix each time we
10236 // actually use it.
10237 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010239 paint.setShader(shader);
10240 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070010241 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010242 }
Romain Guy8506ab42009-06-11 17:35:47 -070010243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010244 public void setFadeColor(int color) {
10245 if (color != 0 && color != mLastColor) {
10246 mLastColor = color;
10247 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070010248
Romain Guye55e1a72009-08-27 10:42:26 -070010249 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
10250 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010252 paint.setShader(shader);
10253 // Restore the default transfer mode (src_over)
10254 paint.setXfermode(null);
10255 }
10256 }
Mike Cleronf116bf82009-09-27 19:14:12 -070010257
10258 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070010259 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070010260 if (now >= fadeStartTime) {
10261
10262 // the animation fades the scrollbars out by changing
10263 // the opacity (alpha) from fully opaque to fully
10264 // transparent
10265 int nextFrame = (int) now;
10266 int framesCount = 0;
10267
10268 Interpolator interpolator = scrollBarInterpolator;
10269
10270 // Start opaque
10271 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
10272
10273 // End transparent
10274 nextFrame += scrollBarFadeDuration;
10275 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
10276
10277 state = FADING;
10278
10279 // Kick off the fade animation
10280 host.invalidate();
10281 }
10282 }
10283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010284 }
10285}