blob: 76814c2b110bb737184f0af179415817d731ed6f [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080019import com.android.internal.R;
20import com.android.internal.util.Predicate;
21import com.android.internal.view.menu.MenuBuilder;
22
Christopher Tatea53146c2010-09-07 11:57:52 -070023import android.content.ClipData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080025import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.res.Resources;
27import android.content.res.TypedArray;
28import android.graphics.Bitmap;
Adam Powell2b342f02010-08-18 18:14:13 -070029import android.graphics.Camera;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.graphics.Canvas;
Mike Cleronf116bf82009-09-27 19:14:12 -070031import android.graphics.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.graphics.LinearGradient;
33import android.graphics.Matrix;
34import android.graphics.Paint;
35import android.graphics.PixelFormat;
svetoslavganov75986cf2009-05-14 22:28:01 -070036import android.graphics.Point;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.graphics.PorterDuff;
38import android.graphics.PorterDuffXfermode;
39import android.graphics.Rect;
Adam Powell6e346362010-07-23 10:18:23 -070040import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.graphics.Region;
42import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.graphics.drawable.ColorDrawable;
44import android.graphics.drawable.Drawable;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Message;
48import android.os.Parcel;
49import android.os.Parcelable;
50import android.os.RemoteException;
51import android.os.SystemClock;
52import android.os.SystemProperties;
53import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070055import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070056import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070057import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070058import android.util.Pools;
59import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.ContextMenu.ContextMenuInfo;
svetoslavganov75986cf2009-05-14 22:28:01 -070061import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070065import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070066import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.view.inputmethod.InputConnection;
68import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.widget.ScrollBarDrawable;
70
Christopher Tatea0374192010-10-05 13:06:41 -070071import java.lang.ref.WeakReference;
svetoslavganov75986cf2009-05-14 22:28:01 -070072import java.lang.reflect.InvocationTargetException;
73import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import java.util.ArrayList;
75import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070076import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070077import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
79/**
80 * <p>
81 * This class represents the basic building block for user interface components. A View
82 * occupies a rectangular area on the screen and is responsible for drawing and
83 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070084 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
86 * are invisible containers that hold other Views (or other ViewGroups) and define
87 * their layout properties.
88 * </p>
89 *
90 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070091 * <p>For an introduction to using this class to develop your
92 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070094 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
102 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
103 * </p>
104 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700105 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 * <a name="Using"></a>
107 * <h3>Using Views</h3>
108 * <p>
109 * All of the views in a window are arranged in a single tree. You can add views
110 * either from code or by specifying a tree of views in one or more XML layout
111 * files. There are many specialized subclasses of views that act as controls or
112 * are capable of displaying text, images, or other content.
113 * </p>
114 * <p>
115 * Once you have created a tree of views, there are typically a few types of
116 * common operations you may wish to perform:
117 * <ul>
118 * <li><strong>Set properties:</strong> for example setting the text of a
119 * {@link android.widget.TextView}. The available properties and the methods
120 * that set them will vary among the different subclasses of views. Note that
121 * properties that are known at build time can be set in the XML layout
122 * files.</li>
123 * <li><strong>Set focus:</strong> The framework will handled moving focus in
124 * response to user input. To force focus to a specific view, call
125 * {@link #requestFocus}.</li>
126 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
127 * that will be notified when something interesting happens to the view. For
128 * example, all views will let you set a listener to be notified when the view
129 * gains or loses focus. You can register such a listener using
130 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
131 * specialized listeners. For example, a Button exposes a listener to notify
132 * clients when the button is clicked.</li>
133 * <li><strong>Set visibility:</strong> You can hide or show views using
134 * {@link #setVisibility}.</li>
135 * </ul>
136 * </p>
137 * <p><em>
138 * Note: The Android framework is responsible for measuring, laying out and
139 * drawing views. You should not call methods that perform these actions on
140 * views yourself unless you are actually implementing a
141 * {@link android.view.ViewGroup}.
142 * </em></p>
143 *
144 * <a name="Lifecycle"></a>
145 * <h3>Implementing a Custom View</h3>
146 *
147 * <p>
148 * To implement a custom view, you will usually begin by providing overrides for
149 * some of the standard methods that the framework calls on all views. You do
150 * not need to override all of these methods. In fact, you can start by just
151 * overriding {@link #onDraw(android.graphics.Canvas)}.
152 * <table border="2" width="85%" align="center" cellpadding="5">
153 * <thead>
154 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
155 * </thead>
156 *
157 * <tbody>
158 * <tr>
159 * <td rowspan="2">Creation</td>
160 * <td>Constructors</td>
161 * <td>There is a form of the constructor that are called when the view
162 * is created from code and a form that is called when the view is
163 * inflated from a layout file. The second form should parse and apply
164 * any attributes defined in the layout file.
165 * </td>
166 * </tr>
167 * <tr>
168 * <td><code>{@link #onFinishInflate()}</code></td>
169 * <td>Called after a view and all of its children has been inflated
170 * from XML.</td>
171 * </tr>
172 *
173 * <tr>
174 * <td rowspan="3">Layout</td>
175 * <td><code>{@link #onMeasure}</code></td>
176 * <td>Called to determine the size requirements for this view and all
177 * of its children.
178 * </td>
179 * </tr>
180 * <tr>
181 * <td><code>{@link #onLayout}</code></td>
182 * <td>Called when this view should assign a size and position to all
183 * of its children.
184 * </td>
185 * </tr>
186 * <tr>
187 * <td><code>{@link #onSizeChanged}</code></td>
188 * <td>Called when the size of this view has changed.
189 * </td>
190 * </tr>
191 *
192 * <tr>
193 * <td>Drawing</td>
194 * <td><code>{@link #onDraw}</code></td>
195 * <td>Called when the view should render its content.
196 * </td>
197 * </tr>
198 *
199 * <tr>
200 * <td rowspan="4">Event processing</td>
201 * <td><code>{@link #onKeyDown}</code></td>
202 * <td>Called when a new key event occurs.
203 * </td>
204 * </tr>
205 * <tr>
206 * <td><code>{@link #onKeyUp}</code></td>
207 * <td>Called when a key up event occurs.
208 * </td>
209 * </tr>
210 * <tr>
211 * <td><code>{@link #onTrackballEvent}</code></td>
212 * <td>Called when a trackball motion event occurs.
213 * </td>
214 * </tr>
215 * <tr>
216 * <td><code>{@link #onTouchEvent}</code></td>
217 * <td>Called when a touch screen motion event occurs.
218 * </td>
219 * </tr>
220 *
221 * <tr>
222 * <td rowspan="2">Focus</td>
223 * <td><code>{@link #onFocusChanged}</code></td>
224 * <td>Called when the view gains or loses focus.
225 * </td>
226 * </tr>
227 *
228 * <tr>
229 * <td><code>{@link #onWindowFocusChanged}</code></td>
230 * <td>Called when the window containing the view gains or loses focus.
231 * </td>
232 * </tr>
233 *
234 * <tr>
235 * <td rowspan="3">Attaching</td>
236 * <td><code>{@link #onAttachedToWindow()}</code></td>
237 * <td>Called when the view is attached to a window.
238 * </td>
239 * </tr>
240 *
241 * <tr>
242 * <td><code>{@link #onDetachedFromWindow}</code></td>
243 * <td>Called when the view is detached from its window.
244 * </td>
245 * </tr>
246 *
247 * <tr>
248 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
249 * <td>Called when the visibility of the window containing the view
250 * has changed.
251 * </td>
252 * </tr>
253 * </tbody>
254 *
255 * </table>
256 * </p>
257 *
258 * <a name="IDs"></a>
259 * <h3>IDs</h3>
260 * Views may have an integer id associated with them. These ids are typically
261 * assigned in the layout XML files, and are used to find specific views within
262 * the view tree. A common pattern is to:
263 * <ul>
264 * <li>Define a Button in the layout file and assign it a unique ID.
265 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700266 * &lt;Button
267 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 * android:layout_width="wrap_content"
269 * android:layout_height="wrap_content"
270 * android:text="@string/my_button_text"/&gt;
271 * </pre></li>
272 * <li>From the onCreate method of an Activity, find the Button
273 * <pre class="prettyprint">
274 * Button myButton = (Button) findViewById(R.id.my_button);
275 * </pre></li>
276 * </ul>
277 * <p>
278 * View IDs need not be unique throughout the tree, but it is good practice to
279 * ensure that they are at least unique within the part of the tree you are
280 * searching.
281 * </p>
282 *
283 * <a name="Position"></a>
284 * <h3>Position</h3>
285 * <p>
286 * The geometry of a view is that of a rectangle. A view has a location,
287 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
288 * two dimensions, expressed as a width and a height. The unit for location
289 * and dimensions is the pixel.
290 * </p>
291 *
292 * <p>
293 * It is possible to retrieve the location of a view by invoking the methods
294 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
295 * coordinate of the rectangle representing the view. The latter returns the
296 * top, or Y, coordinate of the rectangle representing the view. These methods
297 * both return the location of the view relative to its parent. For instance,
298 * when getLeft() returns 20, that means the view is located 20 pixels to the
299 * right of the left edge of its direct parent.
300 * </p>
301 *
302 * <p>
303 * In addition, several convenience methods are offered to avoid unnecessary
304 * computations, namely {@link #getRight()} and {@link #getBottom()}.
305 * These methods return the coordinates of the right and bottom edges of the
306 * rectangle representing the view. For instance, calling {@link #getRight()}
307 * is similar to the following computation: <code>getLeft() + getWidth()</code>
308 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
309 * </p>
310 *
311 * <a name="SizePaddingMargins"></a>
312 * <h3>Size, padding and margins</h3>
313 * <p>
314 * The size of a view is expressed with a width and a height. A view actually
315 * possess two pairs of width and height values.
316 * </p>
317 *
318 * <p>
319 * The first pair is known as <em>measured width</em> and
320 * <em>measured height</em>. These dimensions define how big a view wants to be
321 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
322 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
323 * and {@link #getMeasuredHeight()}.
324 * </p>
325 *
326 * <p>
327 * The second pair is simply known as <em>width</em> and <em>height</em>, or
328 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
329 * dimensions define the actual size of the view on screen, at drawing time and
330 * after layout. These values may, but do not have to, be different from the
331 * measured width and height. The width and height can be obtained by calling
332 * {@link #getWidth()} and {@link #getHeight()}.
333 * </p>
334 *
335 * <p>
336 * To measure its dimensions, a view takes into account its padding. The padding
337 * is expressed in pixels for the left, top, right and bottom parts of the view.
338 * Padding can be used to offset the content of the view by a specific amount of
339 * pixels. For instance, a left padding of 2 will push the view's content by
340 * 2 pixels to the right of the left edge. Padding can be set using the
341 * {@link #setPadding(int, int, int, int)} method and queried by calling
342 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
343 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
344 * </p>
345 *
346 * <p>
347 * Even though a view can define a padding, it does not provide any support for
348 * margins. However, view groups provide such a support. Refer to
349 * {@link android.view.ViewGroup} and
350 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
351 * </p>
352 *
353 * <a name="Layout"></a>
354 * <h3>Layout</h3>
355 * <p>
356 * Layout is a two pass process: a measure pass and a layout pass. The measuring
357 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
358 * of the view tree. Each view pushes dimension specifications down the tree
359 * during the recursion. At the end of the measure pass, every view has stored
360 * its measurements. The second pass happens in
361 * {@link #layout(int,int,int,int)} and is also top-down. During
362 * this pass each parent is responsible for positioning all of its children
363 * using the sizes computed in the measure pass.
364 * </p>
365 *
366 * <p>
367 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
368 * {@link #getMeasuredHeight()} values must be set, along with those for all of
369 * that view's descendants. A view's measured width and measured height values
370 * must respect the constraints imposed by the view's parents. This guarantees
371 * that at the end of the measure pass, all parents accept all of their
372 * children's measurements. A parent view may call measure() more than once on
373 * its children. For example, the parent may measure each child once with
374 * unspecified dimensions to find out how big they want to be, then call
375 * measure() on them again with actual numbers if the sum of all the children's
376 * unconstrained sizes is too big or too small.
377 * </p>
378 *
379 * <p>
380 * The measure pass uses two classes to communicate dimensions. The
381 * {@link MeasureSpec} class is used by views to tell their parents how they
382 * want to be measured and positioned. The base LayoutParams class just
383 * describes how big the view wants to be for both width and height. For each
384 * dimension, it can specify one of:
385 * <ul>
386 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800387 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 * (minus padding)
389 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
390 * enclose its content (plus padding).
391 * </ul>
392 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
393 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
394 * an X and Y value.
395 * </p>
396 *
397 * <p>
398 * MeasureSpecs are used to push requirements down the tree from parent to
399 * child. A MeasureSpec can be in one of three modes:
400 * <ul>
401 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
402 * of a child view. For example, a LinearLayout may call measure() on its child
403 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
404 * tall the child view wants to be given a width of 240 pixels.
405 * <li>EXACTLY: This is used by the parent to impose an exact size on the
406 * child. The child must use this size, and guarantee that all of its
407 * descendants will fit within this size.
408 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
409 * child. The child must gurantee that it and all of its descendants will fit
410 * within this size.
411 * </ul>
412 * </p>
413 *
414 * <p>
415 * To intiate a layout, call {@link #requestLayout}. This method is typically
416 * called by a view on itself when it believes that is can no longer fit within
417 * its current bounds.
418 * </p>
419 *
420 * <a name="Drawing"></a>
421 * <h3>Drawing</h3>
422 * <p>
423 * Drawing is handled by walking the tree and rendering each view that
424 * intersects the the invalid region. Because the tree is traversed in-order,
425 * this means that parents will draw before (i.e., behind) their children, with
426 * siblings drawn in the order they appear in the tree.
427 * If you set a background drawable for a View, then the View will draw it for you
428 * before calling back to its <code>onDraw()</code> method.
429 * </p>
430 *
431 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700432 * Note that the framework will not draw views that are not in the invalid region.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 * </p>
434 *
435 * <p>
436 * To force a view to draw, call {@link #invalidate()}.
437 * </p>
438 *
439 * <a name="EventHandlingThreading"></a>
440 * <h3>Event Handling and Threading</h3>
441 * <p>
442 * The basic cycle of a view is as follows:
443 * <ol>
444 * <li>An event comes in and is dispatched to the appropriate view. The view
445 * handles the event and notifies any listeners.</li>
446 * <li>If in the course of processing the event, the view's bounds may need
447 * to be changed, the view will call {@link #requestLayout()}.</li>
448 * <li>Similarly, if in the course of processing the event the view's appearance
449 * may need to be changed, the view will call {@link #invalidate()}.</li>
450 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
451 * the framework will take care of measuring, laying out, and drawing the tree
452 * as appropriate.</li>
453 * </ol>
454 * </p>
455 *
456 * <p><em>Note: The entire view tree is single threaded. You must always be on
457 * the UI thread when calling any method on any view.</em>
458 * If you are doing work on other threads and want to update the state of a view
459 * from that thread, you should use a {@link Handler}.
460 * </p>
461 *
462 * <a name="FocusHandling"></a>
463 * <h3>Focus Handling</h3>
464 * <p>
465 * The framework will handle routine focus movement in response to user input.
466 * This includes changing the focus as views are removed or hidden, or as new
467 * views become available. Views indicate their willingness to take focus
468 * through the {@link #isFocusable} method. To change whether a view can take
469 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
470 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
471 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
472 * </p>
473 * <p>
474 * Focus movement is based on an algorithm which finds the nearest neighbor in a
475 * given direction. In rare cases, the default algorithm may not match the
476 * intended behavior of the developer. In these situations, you can provide
477 * explicit overrides by using these XML attributes in the layout file:
478 * <pre>
479 * nextFocusDown
480 * nextFocusLeft
481 * nextFocusRight
482 * nextFocusUp
483 * </pre>
484 * </p>
485 *
486 *
487 * <p>
488 * To get a particular view to take focus, call {@link #requestFocus()}.
489 * </p>
490 *
491 * <a name="TouchMode"></a>
492 * <h3>Touch Mode</h3>
493 * <p>
494 * When a user is navigating a user interface via directional keys such as a D-pad, it is
495 * necessary to give focus to actionable items such as buttons so the user can see
496 * what will take input. If the device has touch capabilities, however, and the user
497 * begins interacting with the interface by touching it, it is no longer necessary to
498 * always highlight, or give focus to, a particular view. This motivates a mode
499 * for interaction named 'touch mode'.
500 * </p>
501 * <p>
502 * For a touch capable device, once the user touches the screen, the device
503 * will enter touch mode. From this point onward, only views for which
504 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
505 * Other views that are touchable, like buttons, will not take focus when touched; they will
506 * only fire the on click listeners.
507 * </p>
508 * <p>
509 * Any time a user hits a directional key, such as a D-pad direction, the view device will
510 * exit touch mode, and find a view to take focus, so that the user may resume interacting
511 * with the user interface without touching the screen again.
512 * </p>
513 * <p>
514 * The touch mode state is maintained across {@link android.app.Activity}s. Call
515 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
516 * </p>
517 *
518 * <a name="Scrolling"></a>
519 * <h3>Scrolling</h3>
520 * <p>
521 * The framework provides basic support for views that wish to internally
522 * scroll their content. This includes keeping track of the X and Y scroll
523 * offset as well as mechanisms for drawing scrollbars. See
Joe Malin32736f02011-01-19 16:14:20 -0800524 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
Mike Cleronf116bf82009-09-27 19:14:12 -0700525 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 * </p>
527 *
528 * <a name="Tags"></a>
529 * <h3>Tags</h3>
530 * <p>
531 * Unlike IDs, tags are not used to identify views. Tags are essentially an
532 * extra piece of information that can be associated with a view. They are most
533 * often used as a convenience to store data related to views in the views
534 * themselves rather than by putting them in a separate structure.
535 * </p>
536 *
537 * <a name="Animation"></a>
538 * <h3>Animation</h3>
539 * <p>
540 * You can attach an {@link Animation} object to a view using
541 * {@link #setAnimation(Animation)} or
542 * {@link #startAnimation(Animation)}. The animation can alter the scale,
543 * rotation, translation and alpha of a view over time. If the animation is
544 * attached to a view that has children, the animation will affect the entire
545 * subtree rooted by that node. When an animation is started, the framework will
546 * take care of redrawing the appropriate views until the animation completes.
547 * </p>
Romain Guy171c5922011-01-06 10:04:23 -0800548 * <p>
549 * Starting with Android 3.0, the preferred way of animating views is to use the
550 * {@link android.animation} package APIs.
551 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 *
Jeff Brown85a31762010-09-01 17:01:00 -0700553 * <a name="Security"></a>
554 * <h3>Security</h3>
555 * <p>
556 * Sometimes it is essential that an application be able to verify that an action
557 * is being performed with the full knowledge and consent of the user, such as
558 * granting a permission request, making a purchase or clicking on an advertisement.
559 * Unfortunately, a malicious application could try to spoof the user into
560 * performing these actions, unaware, by concealing the intended purpose of the view.
561 * As a remedy, the framework offers a touch filtering mechanism that can be used to
562 * improve the security of views that provide access to sensitive functionality.
563 * </p><p>
564 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
Jeff Brown49ed71d2010-12-06 17:13:33 -0800565 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework
Jeff Brown85a31762010-09-01 17:01:00 -0700566 * will discard touches that are received whenever the view's window is obscured by
567 * another visible window. As a result, the view will not receive touches whenever a
568 * toast, dialog or other window appears above the view's window.
569 * </p><p>
570 * For more fine-grained control over security, consider overriding the
571 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
572 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
573 * </p>
574 *
Romain Guy171c5922011-01-06 10:04:23 -0800575 * @attr ref android.R.styleable#View_alpha
Romain Guyd6a463a2009-05-21 23:10:10 -0700576 * @attr ref android.R.styleable#View_background
577 * @attr ref android.R.styleable#View_clickable
578 * @attr ref android.R.styleable#View_contentDescription
579 * @attr ref android.R.styleable#View_drawingCacheQuality
580 * @attr ref android.R.styleable#View_duplicateParentState
581 * @attr ref android.R.styleable#View_id
582 * @attr ref android.R.styleable#View_fadingEdge
583 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700584 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700586 * @attr ref android.R.styleable#View_isScrollContainer
587 * @attr ref android.R.styleable#View_focusable
588 * @attr ref android.R.styleable#View_focusableInTouchMode
589 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
590 * @attr ref android.R.styleable#View_keepScreenOn
Romain Guy171c5922011-01-06 10:04:23 -0800591 * @attr ref android.R.styleable#View_layerType
Romain Guyd6a463a2009-05-21 23:10:10 -0700592 * @attr ref android.R.styleable#View_longClickable
593 * @attr ref android.R.styleable#View_minHeight
594 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 * @attr ref android.R.styleable#View_nextFocusDown
596 * @attr ref android.R.styleable#View_nextFocusLeft
597 * @attr ref android.R.styleable#View_nextFocusRight
598 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700599 * @attr ref android.R.styleable#View_onClick
600 * @attr ref android.R.styleable#View_padding
601 * @attr ref android.R.styleable#View_paddingBottom
602 * @attr ref android.R.styleable#View_paddingLeft
603 * @attr ref android.R.styleable#View_paddingRight
604 * @attr ref android.R.styleable#View_paddingTop
605 * @attr ref android.R.styleable#View_saveEnabled
Chet Haase73066682010-11-29 15:55:32 -0800606 * @attr ref android.R.styleable#View_rotation
607 * @attr ref android.R.styleable#View_rotationX
608 * @attr ref android.R.styleable#View_rotationY
609 * @attr ref android.R.styleable#View_scaleX
610 * @attr ref android.R.styleable#View_scaleY
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 * @attr ref android.R.styleable#View_scrollX
612 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700613 * @attr ref android.R.styleable#View_scrollbarSize
614 * @attr ref android.R.styleable#View_scrollbarStyle
615 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700616 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
617 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
619 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 * @attr ref android.R.styleable#View_scrollbarThumbVertical
621 * @attr ref android.R.styleable#View_scrollbarTrackVertical
622 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700624 * @attr ref android.R.styleable#View_soundEffectsEnabled
625 * @attr ref android.R.styleable#View_tag
Chet Haase73066682010-11-29 15:55:32 -0800626 * @attr ref android.R.styleable#View_transformPivotX
627 * @attr ref android.R.styleable#View_transformPivotY
628 * @attr ref android.R.styleable#View_translationX
629 * @attr ref android.R.styleable#View_translationY
Romain Guyd6a463a2009-05-21 23:10:10 -0700630 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 *
632 * @see android.view.ViewGroup
633 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700634public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 private static final boolean DBG = false;
636
637 /**
638 * The logging tag used by this class with android.util.Log.
639 */
640 protected static final String VIEW_LOG_TAG = "View";
641
642 /**
643 * Used to mark a View that has no ID.
644 */
645 public static final int NO_ID = -1;
646
647 /**
648 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
649 * calling setFlags.
650 */
651 private static final int NOT_FOCUSABLE = 0x00000000;
652
653 /**
654 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
655 * setFlags.
656 */
657 private static final int FOCUSABLE = 0x00000001;
658
659 /**
660 * Mask for use with setFlags indicating bits used for focus.
661 */
662 private static final int FOCUSABLE_MASK = 0x00000001;
663
664 /**
665 * This view will adjust its padding to fit sytem windows (e.g. status bar)
666 */
667 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
668
669 /**
670 * This view is visible. Use with {@link #setVisibility}.
671 */
672 public static final int VISIBLE = 0x00000000;
673
674 /**
675 * This view is invisible, but it still takes up space for layout purposes.
676 * Use with {@link #setVisibility}.
677 */
678 public static final int INVISIBLE = 0x00000004;
679
680 /**
681 * This view is invisible, and it doesn't take any space for layout
682 * purposes. Use with {@link #setVisibility}.
683 */
684 public static final int GONE = 0x00000008;
685
686 /**
687 * Mask for use with setFlags indicating bits used for visibility.
688 * {@hide}
689 */
690 static final int VISIBILITY_MASK = 0x0000000C;
691
692 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
693
694 /**
695 * This view is enabled. Intrepretation varies by subclass.
696 * Use with ENABLED_MASK when calling setFlags.
697 * {@hide}
698 */
699 static final int ENABLED = 0x00000000;
700
701 /**
702 * This view is disabled. Intrepretation varies by subclass.
703 * Use with ENABLED_MASK when calling setFlags.
704 * {@hide}
705 */
706 static final int DISABLED = 0x00000020;
707
708 /**
709 * Mask for use with setFlags indicating bits used for indicating whether
710 * this view is enabled
711 * {@hide}
712 */
713 static final int ENABLED_MASK = 0x00000020;
714
715 /**
716 * This view won't draw. {@link #onDraw} won't be called and further
717 * optimizations
718 * will be performed. It is okay to have this flag set and a background.
719 * Use with DRAW_MASK when calling setFlags.
720 * {@hide}
721 */
722 static final int WILL_NOT_DRAW = 0x00000080;
723
724 /**
725 * Mask for use with setFlags indicating bits used for indicating whether
726 * this view is will draw
727 * {@hide}
728 */
729 static final int DRAW_MASK = 0x00000080;
730
731 /**
732 * <p>This view doesn't show scrollbars.</p>
733 * {@hide}
734 */
735 static final int SCROLLBARS_NONE = 0x00000000;
736
737 /**
738 * <p>This view shows horizontal scrollbars.</p>
739 * {@hide}
740 */
741 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
742
743 /**
744 * <p>This view shows vertical scrollbars.</p>
745 * {@hide}
746 */
747 static final int SCROLLBARS_VERTICAL = 0x00000200;
748
749 /**
750 * <p>Mask for use with setFlags indicating bits used for indicating which
751 * scrollbars are enabled.</p>
752 * {@hide}
753 */
754 static final int SCROLLBARS_MASK = 0x00000300;
755
Jeff Brown85a31762010-09-01 17:01:00 -0700756 /**
757 * Indicates that the view should filter touches when its window is obscured.
758 * Refer to the class comments for more information about this security feature.
759 * {@hide}
760 */
761 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
762
763 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764
765 /**
766 * <p>This view doesn't show fading edges.</p>
767 * {@hide}
768 */
769 static final int FADING_EDGE_NONE = 0x00000000;
770
771 /**
772 * <p>This view shows horizontal fading edges.</p>
773 * {@hide}
774 */
775 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
776
777 /**
778 * <p>This view shows vertical fading edges.</p>
779 * {@hide}
780 */
781 static final int FADING_EDGE_VERTICAL = 0x00002000;
782
783 /**
784 * <p>Mask for use with setFlags indicating bits used for indicating which
785 * fading edges are enabled.</p>
786 * {@hide}
787 */
788 static final int FADING_EDGE_MASK = 0x00003000;
789
790 /**
791 * <p>Indicates this view can be clicked. When clickable, a View reacts
792 * to clicks by notifying the OnClickListener.<p>
793 * {@hide}
794 */
795 static final int CLICKABLE = 0x00004000;
796
797 /**
798 * <p>Indicates this view is caching its drawing into a bitmap.</p>
799 * {@hide}
800 */
801 static final int DRAWING_CACHE_ENABLED = 0x00008000;
802
803 /**
804 * <p>Indicates that no icicle should be saved for this view.<p>
805 * {@hide}
806 */
807 static final int SAVE_DISABLED = 0x000010000;
808
809 /**
810 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
811 * property.</p>
812 * {@hide}
813 */
814 static final int SAVE_DISABLED_MASK = 0x000010000;
815
816 /**
817 * <p>Indicates that no drawing cache should ever be created for this view.<p>
818 * {@hide}
819 */
820 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
821
822 /**
823 * <p>Indicates this view can take / keep focus when int touch mode.</p>
824 * {@hide}
825 */
826 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
827
828 /**
829 * <p>Enables low quality mode for the drawing cache.</p>
830 */
831 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
832
833 /**
834 * <p>Enables high quality mode for the drawing cache.</p>
835 */
836 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
837
838 /**
839 * <p>Enables automatic quality mode for the drawing cache.</p>
840 */
841 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
842
843 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
844 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
845 };
846
847 /**
848 * <p>Mask for use with setFlags indicating bits used for the cache
849 * quality property.</p>
850 * {@hide}
851 */
852 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
853
854 /**
855 * <p>
856 * Indicates this view can be long clicked. When long clickable, a View
857 * reacts to long clicks by notifying the OnLongClickListener or showing a
858 * context menu.
859 * </p>
860 * {@hide}
861 */
862 static final int LONG_CLICKABLE = 0x00200000;
863
864 /**
865 * <p>Indicates that this view gets its drawable states from its direct parent
866 * and ignores its original internal states.</p>
867 *
868 * @hide
869 */
870 static final int DUPLICATE_PARENT_STATE = 0x00400000;
871
872 /**
873 * The scrollbar style to display the scrollbars inside the content area,
874 * without increasing the padding. The scrollbars will be overlaid with
875 * translucency on the view's content.
876 */
877 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
878
879 /**
880 * The scrollbar style to display the scrollbars inside the padded area,
881 * increasing the padding of the view. The scrollbars will not overlap the
882 * content area of the view.
883 */
884 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
885
886 /**
887 * The scrollbar style to display the scrollbars at the edge of the view,
888 * without increasing the padding. The scrollbars will be overlaid with
889 * translucency.
890 */
891 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
892
893 /**
894 * The scrollbar style to display the scrollbars at the edge of the view,
895 * increasing the padding of the view. The scrollbars will only overlap the
896 * background, if any.
897 */
898 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
899
900 /**
901 * Mask to check if the scrollbar style is overlay or inset.
902 * {@hide}
903 */
904 static final int SCROLLBARS_INSET_MASK = 0x01000000;
905
906 /**
907 * Mask to check if the scrollbar style is inside or outside.
908 * {@hide}
909 */
910 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
911
912 /**
913 * Mask for scrollbar style.
914 * {@hide}
915 */
916 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
917
918 /**
919 * View flag indicating that the screen should remain on while the
920 * window containing this view is visible to the user. This effectively
921 * takes care of automatically setting the WindowManager's
922 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
923 */
924 public static final int KEEP_SCREEN_ON = 0x04000000;
925
926 /**
927 * View flag indicating whether this view should have sound effects enabled
928 * for events such as clicking and touching.
929 */
930 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
931
932 /**
933 * View flag indicating whether this view should have haptic feedback
934 * enabled for events such as long presses.
935 */
936 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
937
938 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700939 * <p>Indicates that the view hierarchy should stop saving state when
940 * it reaches this view. If state saving is initiated immediately at
941 * the view, it will be allowed.
942 * {@hide}
943 */
944 static final int PARENT_SAVE_DISABLED = 0x20000000;
945
946 /**
947 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
948 * {@hide}
949 */
950 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
951
952 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700953 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
954 * should add all focusable Views regardless if they are focusable in touch mode.
955 */
956 public static final int FOCUSABLES_ALL = 0x00000000;
957
958 /**
959 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
960 * should add only Views focusable in touch mode.
961 */
962 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
963
964 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 * Use with {@link #focusSearch}. Move focus to the previous selectable
966 * item.
967 */
968 public static final int FOCUS_BACKWARD = 0x00000001;
969
970 /**
971 * Use with {@link #focusSearch}. Move focus to the next selectable
972 * item.
973 */
974 public static final int FOCUS_FORWARD = 0x00000002;
975
976 /**
977 * Use with {@link #focusSearch}. Move focus to the left.
978 */
979 public static final int FOCUS_LEFT = 0x00000011;
980
981 /**
982 * Use with {@link #focusSearch}. Move focus up.
983 */
984 public static final int FOCUS_UP = 0x00000021;
985
986 /**
987 * Use with {@link #focusSearch}. Move focus to the right.
988 */
989 public static final int FOCUS_RIGHT = 0x00000042;
990
991 /**
992 * Use with {@link #focusSearch}. Move focus down.
993 */
994 public static final int FOCUS_DOWN = 0x00000082;
995
996 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -0800997 * Bits of {@link #getMeasuredWidthAndState()} and
998 * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
999 */
1000 public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1001
1002 /**
1003 * Bits of {@link #getMeasuredWidthAndState()} and
1004 * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1005 */
1006 public static final int MEASURED_STATE_MASK = 0xff000000;
1007
1008 /**
1009 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1010 * for functions that combine both width and height into a single int,
1011 * such as {@link #getMeasuredState()} and the childState argument of
1012 * {@link #resolveSizeAndState(int, int, int)}.
1013 */
1014 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1015
1016 /**
1017 * Bit of {@link #getMeasuredWidthAndState()} and
1018 * {@link #getMeasuredWidthAndState()} that indicates the measured size
1019 * is smaller that the space the view would like to have.
1020 */
1021 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1022
1023 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 * Base View state sets
1025 */
1026 // Singles
1027 /**
1028 * Indicates the view has no states set. States are used with
1029 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1030 * view depending on its state.
1031 *
1032 * @see android.graphics.drawable.Drawable
1033 * @see #getDrawableState()
1034 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001035 protected static final int[] EMPTY_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 /**
1037 * Indicates the view is enabled. States are used with
1038 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1039 * view depending on its state.
1040 *
1041 * @see android.graphics.drawable.Drawable
1042 * @see #getDrawableState()
1043 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001044 protected static final int[] ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 /**
1046 * Indicates the view is focused. States are used with
1047 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1048 * view depending on its state.
1049 *
1050 * @see android.graphics.drawable.Drawable
1051 * @see #getDrawableState()
1052 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001053 protected static final int[] FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 /**
1055 * Indicates the view is selected. States are used with
1056 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1057 * view depending on its state.
1058 *
1059 * @see android.graphics.drawable.Drawable
1060 * @see #getDrawableState()
1061 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001062 protected static final int[] SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 /**
1064 * Indicates the view is pressed. States are used with
1065 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1066 * view depending on its state.
1067 *
1068 * @see android.graphics.drawable.Drawable
1069 * @see #getDrawableState()
1070 * @hide
1071 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001072 protected static final int[] PRESSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 /**
1074 * Indicates the view's window has focus. States are used with
1075 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1076 * view depending on its state.
1077 *
1078 * @see android.graphics.drawable.Drawable
1079 * @see #getDrawableState()
1080 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001081 protected static final int[] WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 // Doubles
1083 /**
1084 * Indicates the view is enabled and has the focus.
1085 *
1086 * @see #ENABLED_STATE_SET
1087 * @see #FOCUSED_STATE_SET
1088 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001089 protected static final int[] ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 /**
1091 * Indicates the view is enabled and selected.
1092 *
1093 * @see #ENABLED_STATE_SET
1094 * @see #SELECTED_STATE_SET
1095 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001096 protected static final int[] ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 /**
1098 * Indicates the view is enabled and that its window has focus.
1099 *
1100 * @see #ENABLED_STATE_SET
1101 * @see #WINDOW_FOCUSED_STATE_SET
1102 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001103 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 /**
1105 * Indicates the view is focused and selected.
1106 *
1107 * @see #FOCUSED_STATE_SET
1108 * @see #SELECTED_STATE_SET
1109 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001110 protected static final int[] FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 /**
1112 * Indicates the view has the focus and that its window has the focus.
1113 *
1114 * @see #FOCUSED_STATE_SET
1115 * @see #WINDOW_FOCUSED_STATE_SET
1116 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001117 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 /**
1119 * Indicates the view is selected and that its window has the focus.
1120 *
1121 * @see #SELECTED_STATE_SET
1122 * @see #WINDOW_FOCUSED_STATE_SET
1123 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001124 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 // Triples
1126 /**
1127 * Indicates the view is enabled, focused and selected.
1128 *
1129 * @see #ENABLED_STATE_SET
1130 * @see #FOCUSED_STATE_SET
1131 * @see #SELECTED_STATE_SET
1132 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001133 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 /**
1135 * Indicates the view is enabled, focused and its window has the focus.
1136 *
1137 * @see #ENABLED_STATE_SET
1138 * @see #FOCUSED_STATE_SET
1139 * @see #WINDOW_FOCUSED_STATE_SET
1140 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001141 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 /**
1143 * Indicates the view is enabled, selected and its window has the focus.
1144 *
1145 * @see #ENABLED_STATE_SET
1146 * @see #SELECTED_STATE_SET
1147 * @see #WINDOW_FOCUSED_STATE_SET
1148 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001149 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 /**
1151 * Indicates the view is focused, selected and its window has the focus.
1152 *
1153 * @see #FOCUSED_STATE_SET
1154 * @see #SELECTED_STATE_SET
1155 * @see #WINDOW_FOCUSED_STATE_SET
1156 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001157 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 /**
1159 * Indicates the view is enabled, focused, selected and its window
1160 * has the focus.
1161 *
1162 * @see #ENABLED_STATE_SET
1163 * @see #FOCUSED_STATE_SET
1164 * @see #SELECTED_STATE_SET
1165 * @see #WINDOW_FOCUSED_STATE_SET
1166 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001167 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 /**
1169 * Indicates the view is pressed and its window has the focus.
1170 *
1171 * @see #PRESSED_STATE_SET
1172 * @see #WINDOW_FOCUSED_STATE_SET
1173 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001174 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 /**
1176 * Indicates the view is pressed and selected.
1177 *
1178 * @see #PRESSED_STATE_SET
1179 * @see #SELECTED_STATE_SET
1180 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001181 protected static final int[] PRESSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 /**
1183 * Indicates the view is pressed, selected and its window has the focus.
1184 *
1185 * @see #PRESSED_STATE_SET
1186 * @see #SELECTED_STATE_SET
1187 * @see #WINDOW_FOCUSED_STATE_SET
1188 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001189 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 /**
1191 * Indicates the view is pressed and focused.
1192 *
1193 * @see #PRESSED_STATE_SET
1194 * @see #FOCUSED_STATE_SET
1195 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001196 protected static final int[] PRESSED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 /**
1198 * Indicates the view is pressed, focused and its window has the focus.
1199 *
1200 * @see #PRESSED_STATE_SET
1201 * @see #FOCUSED_STATE_SET
1202 * @see #WINDOW_FOCUSED_STATE_SET
1203 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001204 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 /**
1206 * Indicates the view is pressed, focused and selected.
1207 *
1208 * @see #PRESSED_STATE_SET
1209 * @see #SELECTED_STATE_SET
1210 * @see #FOCUSED_STATE_SET
1211 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001212 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 /**
1214 * Indicates the view is pressed, focused, selected and its window has the focus.
1215 *
1216 * @see #PRESSED_STATE_SET
1217 * @see #FOCUSED_STATE_SET
1218 * @see #SELECTED_STATE_SET
1219 * @see #WINDOW_FOCUSED_STATE_SET
1220 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001221 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 /**
1223 * Indicates the view is pressed and enabled.
1224 *
1225 * @see #PRESSED_STATE_SET
1226 * @see #ENABLED_STATE_SET
1227 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001228 protected static final int[] PRESSED_ENABLED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 /**
1230 * Indicates the view is pressed, enabled and its window has the focus.
1231 *
1232 * @see #PRESSED_STATE_SET
1233 * @see #ENABLED_STATE_SET
1234 * @see #WINDOW_FOCUSED_STATE_SET
1235 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001236 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 /**
1238 * Indicates the view is pressed, enabled and selected.
1239 *
1240 * @see #PRESSED_STATE_SET
1241 * @see #ENABLED_STATE_SET
1242 * @see #SELECTED_STATE_SET
1243 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001244 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 /**
1246 * Indicates the view is pressed, enabled, selected and its window has the
1247 * focus.
1248 *
1249 * @see #PRESSED_STATE_SET
1250 * @see #ENABLED_STATE_SET
1251 * @see #SELECTED_STATE_SET
1252 * @see #WINDOW_FOCUSED_STATE_SET
1253 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001254 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 /**
1256 * Indicates the view is pressed, enabled and focused.
1257 *
1258 * @see #PRESSED_STATE_SET
1259 * @see #ENABLED_STATE_SET
1260 * @see #FOCUSED_STATE_SET
1261 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001262 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 /**
1264 * Indicates the view is pressed, enabled, focused and its window has the
1265 * focus.
1266 *
1267 * @see #PRESSED_STATE_SET
1268 * @see #ENABLED_STATE_SET
1269 * @see #FOCUSED_STATE_SET
1270 * @see #WINDOW_FOCUSED_STATE_SET
1271 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001272 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 /**
1274 * Indicates the view is pressed, enabled, focused and selected.
1275 *
1276 * @see #PRESSED_STATE_SET
1277 * @see #ENABLED_STATE_SET
1278 * @see #SELECTED_STATE_SET
1279 * @see #FOCUSED_STATE_SET
1280 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001281 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 /**
1283 * Indicates the view is pressed, enabled, focused, selected and its window
1284 * has the focus.
1285 *
1286 * @see #PRESSED_STATE_SET
1287 * @see #ENABLED_STATE_SET
1288 * @see #SELECTED_STATE_SET
1289 * @see #FOCUSED_STATE_SET
1290 * @see #WINDOW_FOCUSED_STATE_SET
1291 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001292 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293
1294 /**
1295 * The order here is very important to {@link #getDrawableState()}
1296 */
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001297 private static final int[][] VIEW_STATE_SETS;
1298
Romain Guyb051e892010-09-28 19:09:36 -07001299 static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1300 static final int VIEW_STATE_SELECTED = 1 << 1;
1301 static final int VIEW_STATE_FOCUSED = 1 << 2;
1302 static final int VIEW_STATE_ENABLED = 1 << 3;
1303 static final int VIEW_STATE_PRESSED = 1 << 4;
1304 static final int VIEW_STATE_ACTIVATED = 1 << 5;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001305 static final int VIEW_STATE_ACCELERATED = 1 << 6;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001306
1307 static final int[] VIEW_STATE_IDS = new int[] {
1308 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED,
1309 R.attr.state_selected, VIEW_STATE_SELECTED,
1310 R.attr.state_focused, VIEW_STATE_FOCUSED,
1311 R.attr.state_enabled, VIEW_STATE_ENABLED,
1312 R.attr.state_pressed, VIEW_STATE_PRESSED,
1313 R.attr.state_activated, VIEW_STATE_ACTIVATED,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001314 R.attr.state_accelerated, VIEW_STATE_ACCELERATED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 };
1316
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001317 static {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001318 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1319 throw new IllegalStateException(
1320 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1321 }
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001322 int[] orderedIds = new int[VIEW_STATE_IDS.length];
Romain Guyb051e892010-09-28 19:09:36 -07001323 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001324 int viewState = R.styleable.ViewDrawableStates[i];
Romain Guyb051e892010-09-28 19:09:36 -07001325 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001326 if (VIEW_STATE_IDS[j] == viewState) {
Romain Guyb051e892010-09-28 19:09:36 -07001327 orderedIds[i * 2] = viewState;
1328 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001329 }
1330 }
1331 }
Romain Guyb051e892010-09-28 19:09:36 -07001332 final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1333 VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1334 for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001335 int numBits = Integer.bitCount(i);
1336 int[] set = new int[numBits];
1337 int pos = 0;
Romain Guyb051e892010-09-28 19:09:36 -07001338 for (int j = 0; j < orderedIds.length; j += 2) {
1339 if ((i & orderedIds[j+1]) != 0) {
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001340 set[pos++] = orderedIds[j];
1341 }
1342 }
1343 VIEW_STATE_SETS[i] = set;
1344 }
1345
1346 EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1347 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1348 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1349 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1350 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1351 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1352 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1353 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1354 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1355 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1356 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1357 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1358 | VIEW_STATE_FOCUSED];
1359 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1360 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1361 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1362 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1363 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1364 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1365 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1366 | VIEW_STATE_ENABLED];
1367 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1368 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1369 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1370 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1371 | VIEW_STATE_ENABLED];
1372 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1373 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1374 | VIEW_STATE_ENABLED];
1375 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1376 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1377 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1378
1379 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1380 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1381 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1382 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1383 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1384 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1385 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1386 | VIEW_STATE_PRESSED];
1387 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1388 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1389 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1390 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1391 | VIEW_STATE_PRESSED];
1392 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1393 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1394 | VIEW_STATE_PRESSED];
1395 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1396 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1397 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1398 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1399 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1400 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1401 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1402 | VIEW_STATE_PRESSED];
1403 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1404 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1405 | VIEW_STATE_PRESSED];
1406 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1407 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1408 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1409 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1410 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1411 | VIEW_STATE_PRESSED];
1412 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1413 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1414 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1415 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1416 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1417 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1418 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1420 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1421 | VIEW_STATE_PRESSED];
1422 }
1423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 /**
1425 * Used by views that contain lists of items. This state indicates that
1426 * the view is showing the last item.
1427 * @hide
1428 */
1429 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1430 /**
1431 * Used by views that contain lists of items. This state indicates that
1432 * the view is showing the first item.
1433 * @hide
1434 */
1435 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1436 /**
1437 * Used by views that contain lists of items. This state indicates that
1438 * the view is showing the middle item.
1439 * @hide
1440 */
1441 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1442 /**
1443 * Used by views that contain lists of items. This state indicates that
1444 * the view is showing only one item.
1445 * @hide
1446 */
1447 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1448 /**
1449 * Used by views that contain lists of items. This state indicates that
1450 * the view is pressed and showing the last item.
1451 * @hide
1452 */
1453 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1454 /**
1455 * Used by views that contain lists of items. This state indicates that
1456 * the view is pressed and showing the first item.
1457 * @hide
1458 */
1459 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1460 /**
1461 * Used by views that contain lists of items. This state indicates that
1462 * the view is pressed and showing the middle item.
1463 * @hide
1464 */
1465 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1466 /**
1467 * Used by views that contain lists of items. This state indicates that
1468 * the view is pressed and showing only one item.
1469 * @hide
1470 */
1471 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1472
1473 /**
1474 * Temporary Rect currently for use in setBackground(). This will probably
1475 * be extended in the future to hold our own class with more than just
1476 * a Rect. :)
1477 */
1478 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001479
1480 /**
1481 * Map used to store views' tags.
1482 */
1483 private static WeakHashMap<View, SparseArray<Object>> sTags;
1484
1485 /**
1486 * Lock used to access sTags.
1487 */
1488 private static final Object sTagsLock = new Object();
1489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 /**
1491 * The animation currently associated with this view.
1492 * @hide
1493 */
1494 protected Animation mCurrentAnimation = null;
1495
1496 /**
1497 * Width as measured during measure pass.
1498 * {@hide}
1499 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001500 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001501 /*package*/ int mMeasuredWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502
1503 /**
1504 * Height as measured during measure pass.
1505 * {@hide}
1506 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001507 @ViewDebug.ExportedProperty(category = "measurement")
Dianne Hackborn189ee182010-12-02 21:48:53 -08001508 /*package*/ int mMeasuredHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509
1510 /**
Chet Haasedaf98e92011-01-10 14:10:36 -08001511 * Flag to indicate that this view was marked INVALIDATED, or had its display list
1512 * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1513 * its display list. This flag, used only when hw accelerated, allows us to clear the
1514 * flag while retaining this information until it's needed (at getDisplayList() time and
1515 * in drawChild(), when we decide to draw a view's children's display lists into our own).
1516 *
1517 * {@hide}
1518 */
1519 boolean mRecreateDisplayList = false;
1520
1521 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 * The view's identifier.
1523 * {@hide}
1524 *
1525 * @see #setId(int)
1526 * @see #getId()
1527 */
1528 @ViewDebug.ExportedProperty(resolveId = true)
1529 int mID = NO_ID;
1530
1531 /**
1532 * The view's tag.
1533 * {@hide}
1534 *
1535 * @see #setTag(Object)
1536 * @see #getTag()
1537 */
1538 protected Object mTag;
1539
1540 // for mPrivateFlags:
1541 /** {@hide} */
1542 static final int WANTS_FOCUS = 0x00000001;
1543 /** {@hide} */
1544 static final int FOCUSED = 0x00000002;
1545 /** {@hide} */
1546 static final int SELECTED = 0x00000004;
1547 /** {@hide} */
1548 static final int IS_ROOT_NAMESPACE = 0x00000008;
1549 /** {@hide} */
1550 static final int HAS_BOUNDS = 0x00000010;
1551 /** {@hide} */
1552 static final int DRAWN = 0x00000020;
1553 /**
1554 * When this flag is set, this view is running an animation on behalf of its
1555 * children and should therefore not cancel invalidate requests, even if they
1556 * lie outside of this view's bounds.
1557 *
1558 * {@hide}
1559 */
1560 static final int DRAW_ANIMATION = 0x00000040;
1561 /** {@hide} */
1562 static final int SKIP_DRAW = 0x00000080;
1563 /** {@hide} */
1564 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1565 /** {@hide} */
1566 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1567 /** {@hide} */
1568 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1569 /** {@hide} */
1570 static final int MEASURED_DIMENSION_SET = 0x00000800;
1571 /** {@hide} */
1572 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001573 /** {@hide} */
1574 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575
1576 private static final int PRESSED = 0x00004000;
1577
1578 /** {@hide} */
1579 static final int DRAWING_CACHE_VALID = 0x00008000;
1580 /**
1581 * Flag used to indicate that this view should be drawn once more (and only once
1582 * more) after its animation has completed.
1583 * {@hide}
1584 */
1585 static final int ANIMATION_STARTED = 0x00010000;
1586
1587 private static final int SAVE_STATE_CALLED = 0x00020000;
1588
1589 /**
1590 * Indicates that the View returned true when onSetAlpha() was called and that
1591 * the alpha must be restored.
1592 * {@hide}
1593 */
1594 static final int ALPHA_SET = 0x00040000;
1595
1596 /**
1597 * Set by {@link #setScrollContainer(boolean)}.
1598 */
1599 static final int SCROLL_CONTAINER = 0x00080000;
1600
1601 /**
1602 * Set by {@link #setScrollContainer(boolean)}.
1603 */
1604 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1605
1606 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001607 * View flag indicating whether this view was invalidated (fully or partially.)
1608 *
1609 * @hide
1610 */
1611 static final int DIRTY = 0x00200000;
1612
1613 /**
1614 * View flag indicating whether this view was invalidated by an opaque
1615 * invalidate request.
1616 *
1617 * @hide
1618 */
1619 static final int DIRTY_OPAQUE = 0x00400000;
1620
1621 /**
1622 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1623 *
1624 * @hide
1625 */
1626 static final int DIRTY_MASK = 0x00600000;
1627
1628 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001629 * Indicates whether the background is opaque.
1630 *
1631 * @hide
1632 */
1633 static final int OPAQUE_BACKGROUND = 0x00800000;
1634
1635 /**
1636 * Indicates whether the scrollbars are opaque.
1637 *
1638 * @hide
1639 */
1640 static final int OPAQUE_SCROLLBARS = 0x01000000;
1641
1642 /**
1643 * Indicates whether the view is opaque.
1644 *
1645 * @hide
1646 */
1647 static final int OPAQUE_MASK = 0x01800000;
Joe Malin32736f02011-01-19 16:14:20 -08001648
Adam Powelle14579b2009-12-16 18:39:52 -08001649 /**
1650 * Indicates a prepressed state;
1651 * the short time between ACTION_DOWN and recognizing
1652 * a 'real' press. Prepressed is used to recognize quick taps
1653 * even when they are shorter than ViewConfiguration.getTapTimeout().
Joe Malin32736f02011-01-19 16:14:20 -08001654 *
Adam Powelle14579b2009-12-16 18:39:52 -08001655 * @hide
1656 */
1657 private static final int PREPRESSED = 0x02000000;
Joe Malin32736f02011-01-19 16:14:20 -08001658
Adam Powellc9fbaab2010-02-16 17:16:19 -08001659 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001660 * Indicates whether the view is temporarily detached.
1661 *
1662 * @hide
1663 */
1664 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Joe Malin32736f02011-01-19 16:14:20 -08001665
Adam Powell8568c3a2010-04-19 14:26:11 -07001666 /**
1667 * Indicates that we should awaken scroll bars once attached
Joe Malin32736f02011-01-19 16:14:20 -08001668 *
Adam Powell8568c3a2010-04-19 14:26:11 -07001669 * @hide
1670 */
1671 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001672
1673 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001674 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1675 * for transform operations
1676 *
1677 * @hide
1678 */
Adam Powellf37df072010-09-17 16:22:49 -07001679 private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
Chet Haasefd2b0022010-08-06 13:08:56 -07001680
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001681 /** {@hide} */
Adam Powellf37df072010-09-17 16:22:49 -07001682 static final int ACTIVATED = 0x40000000;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001683
Chet Haasefd2b0022010-08-06 13:08:56 -07001684 /**
Chet Haasedaf98e92011-01-10 14:10:36 -08001685 * Indicates that this view was specifically invalidated, not just dirtied because some
1686 * child view was invalidated. The flag is used to determine when we need to recreate
1687 * a view's display list (as opposed to just returning a reference to its existing
1688 * display list).
1689 *
1690 * @hide
1691 */
1692 static final int INVALIDATED = 0x80000000;
1693
1694 /**
Adam Powell637d3372010-08-25 14:37:03 -07001695 * Always allow a user to over-scroll this view, provided it is a
1696 * view that can scroll.
1697 *
1698 * @see #getOverScrollMode()
1699 * @see #setOverScrollMode(int)
1700 */
1701 public static final int OVER_SCROLL_ALWAYS = 0;
1702
1703 /**
1704 * Allow a user to over-scroll this view only if the content is large
1705 * enough to meaningfully scroll, provided it is a view that can scroll.
1706 *
1707 * @see #getOverScrollMode()
1708 * @see #setOverScrollMode(int)
1709 */
1710 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1711
1712 /**
1713 * Never allow a user to over-scroll this view.
1714 *
1715 * @see #getOverScrollMode()
1716 * @see #setOverScrollMode(int)
1717 */
1718 public static final int OVER_SCROLL_NEVER = 2;
1719
1720 /**
Joe Onorato664644d2011-01-23 17:53:23 -08001721 * View has requested the status bar to be visible (the default).
1722 *
Joe Malin32736f02011-01-19 16:14:20 -08001723 * @see #setSystemUiVisibility(int)
Joe Onorato664644d2011-01-23 17:53:23 -08001724 */
1725 public static final int STATUS_BAR_VISIBLE = 0;
1726
1727 /**
1728 * View has requested the status bar to be visible (the default).
1729 *
Joe Malin32736f02011-01-19 16:14:20 -08001730 * @see #setSystemUiVisibility(int)
Joe Onorato664644d2011-01-23 17:53:23 -08001731 */
1732 public static final int STATUS_BAR_HIDDEN = 0x00000001;
1733
1734 /**
Adam Powell637d3372010-08-25 14:37:03 -07001735 * Controls the over-scroll mode for this view.
1736 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1737 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1738 * and {@link #OVER_SCROLL_NEVER}.
1739 */
1740 private int mOverScrollMode;
1741
1742 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 * The parent this view is attached to.
1744 * {@hide}
1745 *
1746 * @see #getParent()
1747 */
1748 protected ViewParent mParent;
1749
1750 /**
1751 * {@hide}
1752 */
1753 AttachInfo mAttachInfo;
1754
1755 /**
1756 * {@hide}
1757 */
Romain Guy809a7f62009-05-14 15:44:42 -07001758 @ViewDebug.ExportedProperty(flagMapping = {
1759 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1760 name = "FORCE_LAYOUT"),
1761 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1762 name = "LAYOUT_REQUIRED"),
1763 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001764 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001765 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1766 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1767 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1768 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1769 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 int mPrivateFlags;
1771
1772 /**
Joe Onorato664644d2011-01-23 17:53:23 -08001773 * This view's request for the visibility of the status bar.
1774 * @hide
1775 */
1776 int mSystemUiVisibility;
1777
1778 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 * Count of how many windows this view has been attached to.
1780 */
1781 int mWindowAttachCount;
1782
1783 /**
1784 * The layout parameters associated with this view and used by the parent
1785 * {@link android.view.ViewGroup} to determine how this view should be
1786 * laid out.
1787 * {@hide}
1788 */
1789 protected ViewGroup.LayoutParams mLayoutParams;
1790
1791 /**
1792 * The view flags hold various views states.
1793 * {@hide}
1794 */
1795 @ViewDebug.ExportedProperty
1796 int mViewFlags;
1797
1798 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001799 * The transform matrix for the View. This transform is calculated internally
1800 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1801 * is used by default. Do *not* use this variable directly; instead call
1802 * getMatrix(), which will automatically recalculate the matrix if necessary
1803 * to get the correct matrix based on the latest rotation and scale properties.
1804 */
1805 private final Matrix mMatrix = new Matrix();
1806
1807 /**
1808 * The transform matrix for the View. This transform is calculated internally
1809 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1810 * is used by default. Do *not* use this variable directly; instead call
Jeff Brown86671742010-09-30 20:00:15 -07001811 * getInverseMatrix(), which will automatically recalculate the matrix if necessary
Chet Haasec3aa3612010-06-17 08:50:37 -07001812 * to get the correct matrix based on the latest rotation and scale properties.
1813 */
1814 private Matrix mInverseMatrix;
1815
1816 /**
1817 * An internal variable that tracks whether we need to recalculate the
1818 * transform matrix, based on whether the rotation or scaleX/Y properties
1819 * have changed since the matrix was last calculated.
1820 */
1821 private boolean mMatrixDirty = false;
1822
1823 /**
1824 * An internal variable that tracks whether we need to recalculate the
1825 * transform matrix, based on whether the rotation or scaleX/Y properties
1826 * have changed since the matrix was last calculated.
1827 */
1828 private boolean mInverseMatrixDirty = true;
1829
1830 /**
1831 * A variable that tracks whether we need to recalculate the
1832 * transform matrix, based on whether the rotation or scaleX/Y properties
1833 * have changed since the matrix was last calculated. This variable
Jeff Brown86671742010-09-30 20:00:15 -07001834 * is only valid after a call to updateMatrix() or to a function that
1835 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
Chet Haasec3aa3612010-06-17 08:50:37 -07001836 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001837 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001838
1839 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001840 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1841 */
1842 private Camera mCamera = null;
1843
1844 /**
1845 * This matrix is used when computing the matrix for 3D rotations.
1846 */
1847 private Matrix matrix3D = null;
1848
1849 /**
1850 * These prev values are used to recalculate a centered pivot point when necessary. The
1851 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1852 * set), so thes values are only used then as well.
1853 */
1854 private int mPrevWidth = -1;
1855 private int mPrevHeight = -1;
1856
Joe Malin32736f02011-01-19 16:14:20 -08001857 private boolean mLastIsOpaque;
1858
Chet Haasefd2b0022010-08-06 13:08:56 -07001859 /**
1860 * Convenience value to check for float values that are close enough to zero to be considered
1861 * zero.
1862 */
Romain Guy2542d192010-08-18 11:47:12 -07001863 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001864
1865 /**
1866 * The degrees rotation around the vertical axis through the pivot point.
1867 */
1868 @ViewDebug.ExportedProperty
1869 private float mRotationY = 0f;
1870
1871 /**
1872 * The degrees rotation around the horizontal axis through the pivot point.
1873 */
1874 @ViewDebug.ExportedProperty
1875 private float mRotationX = 0f;
1876
1877 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001878 * The degrees rotation around the pivot point.
1879 */
1880 @ViewDebug.ExportedProperty
1881 private float mRotation = 0f;
1882
1883 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001884 * The amount of translation of the object away from its left property (post-layout).
1885 */
1886 @ViewDebug.ExportedProperty
1887 private float mTranslationX = 0f;
1888
1889 /**
1890 * The amount of translation of the object away from its top property (post-layout).
1891 */
1892 @ViewDebug.ExportedProperty
1893 private float mTranslationY = 0f;
1894
1895 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001896 * The amount of scale in the x direction around the pivot point. A
1897 * value of 1 means no scaling is applied.
1898 */
1899 @ViewDebug.ExportedProperty
1900 private float mScaleX = 1f;
1901
1902 /**
1903 * The amount of scale in the y direction around the pivot point. A
1904 * value of 1 means no scaling is applied.
1905 */
1906 @ViewDebug.ExportedProperty
1907 private float mScaleY = 1f;
1908
1909 /**
1910 * The amount of scale in the x direction around the pivot point. A
1911 * value of 1 means no scaling is applied.
1912 */
1913 @ViewDebug.ExportedProperty
1914 private float mPivotX = 0f;
1915
1916 /**
1917 * The amount of scale in the y direction around the pivot point. A
1918 * value of 1 means no scaling is applied.
1919 */
1920 @ViewDebug.ExportedProperty
1921 private float mPivotY = 0f;
1922
1923 /**
1924 * The opacity of the View. This is a value from 0 to 1, where 0 means
1925 * completely transparent and 1 means completely opaque.
1926 */
1927 @ViewDebug.ExportedProperty
1928 private float mAlpha = 1f;
1929
1930 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 * The distance in pixels from the left edge of this view's parent
1932 * to the left edge of this view.
1933 * {@hide}
1934 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001935 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 protected int mLeft;
1937 /**
1938 * The distance in pixels from the left edge of this view's parent
1939 * to the right edge of this view.
1940 * {@hide}
1941 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001942 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 protected int mRight;
1944 /**
1945 * The distance in pixels from the top edge of this view's parent
1946 * to the top edge of this view.
1947 * {@hide}
1948 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001949 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 protected int mTop;
1951 /**
1952 * The distance in pixels from the top edge of this view's parent
1953 * to the bottom edge of this view.
1954 * {@hide}
1955 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001956 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 protected int mBottom;
1958
1959 /**
1960 * The offset, in pixels, by which the content of this view is scrolled
1961 * horizontally.
1962 * {@hide}
1963 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001964 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 protected int mScrollX;
1966 /**
1967 * The offset, in pixels, by which the content of this view is scrolled
1968 * vertically.
1969 * {@hide}
1970 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001971 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 protected int mScrollY;
1973
1974 /**
1975 * The left padding in pixels, that is the distance in pixels between the
1976 * left edge of this view and the left edge of its content.
1977 * {@hide}
1978 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001979 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 protected int mPaddingLeft;
1981 /**
1982 * The right padding in pixels, that is the distance in pixels between the
1983 * right edge of this view and the right edge of its content.
1984 * {@hide}
1985 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001986 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 protected int mPaddingRight;
1988 /**
1989 * The top padding in pixels, that is the distance in pixels between the
1990 * top edge of this view and the top edge of its content.
1991 * {@hide}
1992 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001993 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 protected int mPaddingTop;
1995 /**
1996 * The bottom padding in pixels, that is the distance in pixels between the
1997 * bottom edge of this view and the bottom edge of its content.
1998 * {@hide}
1999 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002000 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 protected int mPaddingBottom;
2002
2003 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002004 * Briefly describes the view and is primarily used for accessibility support.
2005 */
2006 private CharSequence mContentDescription;
2007
2008 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 * Cache the paddingRight set by the user to append to the scrollbar's size.
2010 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002011 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 int mUserPaddingRight;
2013
2014 /**
2015 * Cache the paddingBottom set by the user to append to the scrollbar's size.
2016 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002017 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 int mUserPaddingBottom;
2019
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002020 /**
Adam Powell20232d02010-12-08 21:08:53 -08002021 * Cache the paddingLeft set by the user to append to the scrollbar's size.
2022 */
2023 @ViewDebug.ExportedProperty(category = "padding")
2024 int mUserPaddingLeft;
2025
2026 /**
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002027 * @hide
2028 */
2029 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2030 /**
2031 * @hide
2032 */
2033 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034
2035 private Resources mResources = null;
2036
2037 private Drawable mBGDrawable;
2038
2039 private int mBackgroundResource;
2040 private boolean mBackgroundSizeChanged;
2041
2042 /**
2043 * Listener used to dispatch focus change events.
2044 * This field should be made private, so it is hidden from the SDK.
2045 * {@hide}
2046 */
2047 protected OnFocusChangeListener mOnFocusChangeListener;
2048
2049 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002050 * Listeners for layout change events.
2051 */
2052 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2053
2054 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 * Listener used to dispatch click events.
2056 * This field should be made private, so it is hidden from the SDK.
2057 * {@hide}
2058 */
2059 protected OnClickListener mOnClickListener;
2060
2061 /**
2062 * Listener used to dispatch long click events.
2063 * This field should be made private, so it is hidden from the SDK.
2064 * {@hide}
2065 */
2066 protected OnLongClickListener mOnLongClickListener;
2067
2068 /**
2069 * Listener used to build the context menu.
2070 * This field should be made private, so it is hidden from the SDK.
2071 * {@hide}
2072 */
2073 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2074
2075 private OnKeyListener mOnKeyListener;
2076
2077 private OnTouchListener mOnTouchListener;
2078
Chris Tate32affef2010-10-18 15:29:21 -07002079 private OnDragListener mOnDragListener;
2080
Joe Onorato664644d2011-01-23 17:53:23 -08002081 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 /**
2084 * The application environment this view lives in.
2085 * This field should be made private, so it is hidden from the SDK.
2086 * {@hide}
2087 */
2088 protected Context mContext;
2089
2090 private ScrollabilityCache mScrollCache;
2091
2092 private int[] mDrawableState = null;
2093
Romain Guy02890fd2010-08-06 17:58:44 -07002094 private Bitmap mDrawingCache;
2095 private Bitmap mUnscaledDrawingCache;
Romain Guyb051e892010-09-28 19:09:36 -07002096 private DisplayList mDisplayList;
Romain Guy6c319ca2011-01-11 14:29:25 -08002097 private HardwareLayer mHardwareLayer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098
2099 /**
2100 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2101 * the user may specify which view to go to next.
2102 */
2103 private int mNextFocusLeftId = View.NO_ID;
2104
2105 /**
2106 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2107 * the user may specify which view to go to next.
2108 */
2109 private int mNextFocusRightId = View.NO_ID;
2110
2111 /**
2112 * When this view has focus and the next focus is {@link #FOCUS_UP},
2113 * the user may specify which view to go to next.
2114 */
2115 private int mNextFocusUpId = View.NO_ID;
2116
2117 /**
2118 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2119 * the user may specify which view to go to next.
2120 */
2121 private int mNextFocusDownId = View.NO_ID;
2122
Jeff Brown4e6319b2010-12-13 10:36:51 -08002123 /**
2124 * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2125 * the user may specify which view to go to next.
2126 */
2127 int mNextFocusForwardId = View.NO_ID;
2128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08002130 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08002131 private PerformClick mPerformClick;
Joe Malin32736f02011-01-19 16:14:20 -08002132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 private UnsetPressedState mUnsetPressedState;
2134
2135 /**
2136 * Whether the long press's action has been invoked. The tap's action is invoked on the
2137 * up event while a long press is invoked as soon as the long press duration is reached, so
2138 * a long press could be performed before the tap is checked, in which case the tap's action
2139 * should not be invoked.
2140 */
2141 private boolean mHasPerformedLongPress;
2142
2143 /**
2144 * The minimum height of the view. We'll try our best to have the height
2145 * of this view to at least this amount.
2146 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002147 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 private int mMinHeight;
2149
2150 /**
2151 * The minimum width of the view. We'll try our best to have the width
2152 * of this view to at least this amount.
2153 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002154 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 private int mMinWidth;
2156
2157 /**
2158 * The delegate to handle touch events that are physically in this view
2159 * but should be handled by another view.
2160 */
2161 private TouchDelegate mTouchDelegate = null;
2162
2163 /**
2164 * Solid color to use as a background when creating the drawing cache. Enables
2165 * the cache to use 16 bit bitmaps instead of 32 bit.
2166 */
2167 private int mDrawingCacheBackgroundColor = 0;
2168
2169 /**
2170 * Special tree observer used when mAttachInfo is null.
2171 */
2172 private ViewTreeObserver mFloatingTreeObserver;
Joe Malin32736f02011-01-19 16:14:20 -08002173
Adam Powelle14579b2009-12-16 18:39:52 -08002174 /**
2175 * Cache the touch slop from the context that created the view.
2176 */
2177 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 /**
Christopher Tatea53146c2010-09-07 11:57:52 -07002180 * Cache drag/drop state
2181 *
2182 */
2183 boolean mCanAcceptDrop;
Christopher Tatea53146c2010-09-07 11:57:52 -07002184
2185 /**
Christopher Tate02d2b3b2011-01-10 20:43:53 -08002186 * Flag indicating that a drag can cross window boundaries
2187 * @hide
2188 */
2189 public static final int DRAG_FLAG_GLOBAL = 1;
2190
2191 /**
Adam Powell20232d02010-12-08 21:08:53 -08002192 * Position of the vertical scroll bar.
2193 */
2194 private int mVerticalScrollbarPosition;
2195
2196 /**
2197 * Position the scroll bar at the default position as determined by the system.
2198 */
2199 public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2200
2201 /**
2202 * Position the scroll bar along the left edge.
2203 */
2204 public static final int SCROLLBAR_POSITION_LEFT = 1;
2205
2206 /**
2207 * Position the scroll bar along the right edge.
2208 */
2209 public static final int SCROLLBAR_POSITION_RIGHT = 2;
2210
2211 /**
Romain Guy171c5922011-01-06 10:04:23 -08002212 * Indicates that the view does not have a layer.
Joe Malin32736f02011-01-19 16:14:20 -08002213 *
2214 * @see #getLayerType()
2215 * @see #setLayerType(int, android.graphics.Paint)
Romain Guy171c5922011-01-06 10:04:23 -08002216 * @see #LAYER_TYPE_SOFTWARE
Joe Malin32736f02011-01-19 16:14:20 -08002217 * @see #LAYER_TYPE_HARDWARE
Romain Guy171c5922011-01-06 10:04:23 -08002218 */
2219 public static final int LAYER_TYPE_NONE = 0;
2220
2221 /**
2222 * <p>Indicates that the view has a software layer. A software layer is backed
2223 * by a bitmap and causes the view to be rendered using Android's software
2224 * rendering pipeline, even if hardware acceleration is enabled.</p>
Joe Malin32736f02011-01-19 16:14:20 -08002225 *
Romain Guy171c5922011-01-06 10:04:23 -08002226 * <p>Software layers have various usages:</p>
2227 * <p>When the application is not using hardware acceleration, a software layer
2228 * is useful to apply a specific color filter and/or blending mode and/or
2229 * translucency to a view and all its children.</p>
2230 * <p>When the application is using hardware acceleration, a software layer
2231 * is useful to render drawing primitives not supported by the hardware
2232 * accelerated pipeline. It can also be used to cache a complex view tree
2233 * into a texture and reduce the complexity of drawing operations. For instance,
2234 * when animating a complex view tree with a translation, a software layer can
2235 * be used to render the view tree only once.</p>
2236 * <p>Software layers should be avoided when the affected view tree updates
2237 * often. Every update will require to re-render the software layer, which can
2238 * potentially be slow (particularly when hardware acceleration is turned on
2239 * since the layer will have to be uploaded into a hardware texture after every
2240 * update.)</p>
Joe Malin32736f02011-01-19 16:14:20 -08002241 *
2242 * @see #getLayerType()
2243 * @see #setLayerType(int, android.graphics.Paint)
Romain Guy171c5922011-01-06 10:04:23 -08002244 * @see #LAYER_TYPE_NONE
Joe Malin32736f02011-01-19 16:14:20 -08002245 * @see #LAYER_TYPE_HARDWARE
Romain Guy171c5922011-01-06 10:04:23 -08002246 */
2247 public static final int LAYER_TYPE_SOFTWARE = 1;
2248
2249 /**
2250 * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2251 * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2252 * OpenGL hardware) and causes the view to be rendered using Android's hardware
2253 * rendering pipeline, but only if hardware acceleration is turned on for the
2254 * view hierarchy. When hardware acceleration is turned off, hardware layers
2255 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
Joe Malin32736f02011-01-19 16:14:20 -08002256 *
Romain Guy171c5922011-01-06 10:04:23 -08002257 * <p>A hardware layer is useful to apply a specific color filter and/or
2258 * blending mode and/or translucency to a view and all its children.</p>
Romain Guy6c319ca2011-01-11 14:29:25 -08002259 * <p>A hardware layer can be used to cache a complex view tree into a
2260 * texture and reduce the complexity of drawing operations. For instance,
2261 * when animating a complex view tree with a translation, a hardware layer can
2262 * be used to render the view tree only once.</p>
Romain Guy171c5922011-01-06 10:04:23 -08002263 * <p>A hardware layer can also be used to increase the rendering quality when
2264 * rotation transformations are applied on a view. It can also be used to
2265 * prevent potential clipping issues when applying 3D transforms on a view.</p>
Joe Malin32736f02011-01-19 16:14:20 -08002266 *
2267 * @see #getLayerType()
Romain Guy171c5922011-01-06 10:04:23 -08002268 * @see #setLayerType(int, android.graphics.Paint)
2269 * @see #LAYER_TYPE_NONE
2270 * @see #LAYER_TYPE_SOFTWARE
2271 */
2272 public static final int LAYER_TYPE_HARDWARE = 2;
Joe Malin32736f02011-01-19 16:14:20 -08002273
Romain Guy3aaff3a2011-01-12 14:18:47 -08002274 @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2275 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2276 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2277 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2278 })
Romain Guy171c5922011-01-06 10:04:23 -08002279 int mLayerType = LAYER_TYPE_NONE;
2280 Paint mLayerPaint;
2281
2282 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 * Simple constructor to use when creating a view from code.
2284 *
2285 * @param context The Context the view is running in, through which it can
2286 * access the current theme, resources, etc.
2287 */
2288 public View(Context context) {
2289 mContext = context;
2290 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07002291 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08002292 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
Adam Powell637d3372010-08-25 14:37:03 -07002293 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 }
2295
2296 /**
2297 * Constructor that is called when inflating a view from XML. This is called
2298 * when a view is being constructed from an XML file, supplying attributes
2299 * that were specified in the XML file. This version uses a default style of
2300 * 0, so the only attribute values applied are those in the Context's Theme
2301 * and the given AttributeSet.
2302 *
2303 * <p>
2304 * The method onFinishInflate() will be called after all children have been
2305 * added.
2306 *
2307 * @param context The Context the view is running in, through which it can
2308 * access the current theme, resources, etc.
2309 * @param attrs The attributes of the XML tag that is inflating the view.
2310 * @see #View(Context, AttributeSet, int)
2311 */
2312 public View(Context context, AttributeSet attrs) {
2313 this(context, attrs, 0);
2314 }
2315
2316 /**
2317 * Perform inflation from XML and apply a class-specific base style. This
2318 * constructor of View allows subclasses to use their own base style when
2319 * they are inflating. For example, a Button class's constructor would call
2320 * this version of the super class constructor and supply
2321 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2322 * the theme's button style to modify all of the base view attributes (in
2323 * particular its background) as well as the Button class's attributes.
2324 *
2325 * @param context The Context the view is running in, through which it can
2326 * access the current theme, resources, etc.
2327 * @param attrs The attributes of the XML tag that is inflating the view.
2328 * @param defStyle The default style to apply to this view. If 0, no style
2329 * will be applied (beyond what is included in the theme). This may
2330 * either be an attribute resource, whose value will be retrieved
2331 * from the current theme, or an explicit style resource.
2332 * @see #View(Context, AttributeSet)
2333 */
2334 public View(Context context, AttributeSet attrs, int defStyle) {
2335 this(context);
2336
2337 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2338 defStyle, 0);
2339
2340 Drawable background = null;
2341
2342 int leftPadding = -1;
2343 int topPadding = -1;
2344 int rightPadding = -1;
2345 int bottomPadding = -1;
2346
2347 int padding = -1;
2348
2349 int viewFlagValues = 0;
2350 int viewFlagMasks = 0;
2351
2352 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 int x = 0;
2355 int y = 0;
2356
Chet Haase73066682010-11-29 15:55:32 -08002357 float tx = 0;
2358 float ty = 0;
2359 float rotation = 0;
2360 float rotationX = 0;
2361 float rotationY = 0;
2362 float sx = 1f;
2363 float sy = 1f;
2364 boolean transformSet = false;
2365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2367
Adam Powell637d3372010-08-25 14:37:03 -07002368 int overScrollMode = mOverScrollMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 final int N = a.getIndexCount();
2370 for (int i = 0; i < N; i++) {
2371 int attr = a.getIndex(i);
2372 switch (attr) {
2373 case com.android.internal.R.styleable.View_background:
2374 background = a.getDrawable(attr);
2375 break;
2376 case com.android.internal.R.styleable.View_padding:
2377 padding = a.getDimensionPixelSize(attr, -1);
2378 break;
2379 case com.android.internal.R.styleable.View_paddingLeft:
2380 leftPadding = a.getDimensionPixelSize(attr, -1);
2381 break;
2382 case com.android.internal.R.styleable.View_paddingTop:
2383 topPadding = a.getDimensionPixelSize(attr, -1);
2384 break;
2385 case com.android.internal.R.styleable.View_paddingRight:
2386 rightPadding = a.getDimensionPixelSize(attr, -1);
2387 break;
2388 case com.android.internal.R.styleable.View_paddingBottom:
2389 bottomPadding = a.getDimensionPixelSize(attr, -1);
2390 break;
2391 case com.android.internal.R.styleable.View_scrollX:
2392 x = a.getDimensionPixelOffset(attr, 0);
2393 break;
2394 case com.android.internal.R.styleable.View_scrollY:
2395 y = a.getDimensionPixelOffset(attr, 0);
2396 break;
Chet Haase73066682010-11-29 15:55:32 -08002397 case com.android.internal.R.styleable.View_alpha:
2398 setAlpha(a.getFloat(attr, 1f));
2399 break;
2400 case com.android.internal.R.styleable.View_transformPivotX:
2401 setPivotX(a.getDimensionPixelOffset(attr, 0));
2402 break;
2403 case com.android.internal.R.styleable.View_transformPivotY:
2404 setPivotY(a.getDimensionPixelOffset(attr, 0));
2405 break;
2406 case com.android.internal.R.styleable.View_translationX:
2407 tx = a.getDimensionPixelOffset(attr, 0);
2408 transformSet = true;
2409 break;
2410 case com.android.internal.R.styleable.View_translationY:
2411 ty = a.getDimensionPixelOffset(attr, 0);
2412 transformSet = true;
2413 break;
2414 case com.android.internal.R.styleable.View_rotation:
2415 rotation = a.getFloat(attr, 0);
2416 transformSet = true;
2417 break;
2418 case com.android.internal.R.styleable.View_rotationX:
2419 rotationX = a.getFloat(attr, 0);
2420 transformSet = true;
2421 break;
2422 case com.android.internal.R.styleable.View_rotationY:
2423 rotationY = a.getFloat(attr, 0);
2424 transformSet = true;
2425 break;
2426 case com.android.internal.R.styleable.View_scaleX:
2427 sx = a.getFloat(attr, 1f);
2428 transformSet = true;
2429 break;
2430 case com.android.internal.R.styleable.View_scaleY:
2431 sy = a.getFloat(attr, 1f);
2432 transformSet = true;
2433 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 case com.android.internal.R.styleable.View_id:
2435 mID = a.getResourceId(attr, NO_ID);
2436 break;
2437 case com.android.internal.R.styleable.View_tag:
2438 mTag = a.getText(attr);
2439 break;
2440 case com.android.internal.R.styleable.View_fitsSystemWindows:
2441 if (a.getBoolean(attr, false)) {
2442 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2443 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2444 }
2445 break;
2446 case com.android.internal.R.styleable.View_focusable:
2447 if (a.getBoolean(attr, false)) {
2448 viewFlagValues |= FOCUSABLE;
2449 viewFlagMasks |= FOCUSABLE_MASK;
2450 }
2451 break;
2452 case com.android.internal.R.styleable.View_focusableInTouchMode:
2453 if (a.getBoolean(attr, false)) {
2454 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2455 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2456 }
2457 break;
2458 case com.android.internal.R.styleable.View_clickable:
2459 if (a.getBoolean(attr, false)) {
2460 viewFlagValues |= CLICKABLE;
2461 viewFlagMasks |= CLICKABLE;
2462 }
2463 break;
2464 case com.android.internal.R.styleable.View_longClickable:
2465 if (a.getBoolean(attr, false)) {
2466 viewFlagValues |= LONG_CLICKABLE;
2467 viewFlagMasks |= LONG_CLICKABLE;
2468 }
2469 break;
2470 case com.android.internal.R.styleable.View_saveEnabled:
2471 if (!a.getBoolean(attr, true)) {
2472 viewFlagValues |= SAVE_DISABLED;
2473 viewFlagMasks |= SAVE_DISABLED_MASK;
2474 }
2475 break;
2476 case com.android.internal.R.styleable.View_duplicateParentState:
2477 if (a.getBoolean(attr, false)) {
2478 viewFlagValues |= DUPLICATE_PARENT_STATE;
2479 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2480 }
2481 break;
2482 case com.android.internal.R.styleable.View_visibility:
2483 final int visibility = a.getInt(attr, 0);
2484 if (visibility != 0) {
2485 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2486 viewFlagMasks |= VISIBILITY_MASK;
2487 }
2488 break;
2489 case com.android.internal.R.styleable.View_drawingCacheQuality:
2490 final int cacheQuality = a.getInt(attr, 0);
2491 if (cacheQuality != 0) {
2492 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2493 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2494 }
2495 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002496 case com.android.internal.R.styleable.View_contentDescription:
2497 mContentDescription = a.getString(attr);
2498 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2500 if (!a.getBoolean(attr, true)) {
2501 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2502 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2503 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002504 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2506 if (!a.getBoolean(attr, true)) {
2507 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2508 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2509 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002510 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 case R.styleable.View_scrollbars:
2512 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2513 if (scrollbars != SCROLLBARS_NONE) {
2514 viewFlagValues |= scrollbars;
2515 viewFlagMasks |= SCROLLBARS_MASK;
2516 initializeScrollbars(a);
2517 }
2518 break;
2519 case R.styleable.View_fadingEdge:
2520 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2521 if (fadingEdge != FADING_EDGE_NONE) {
2522 viewFlagValues |= fadingEdge;
2523 viewFlagMasks |= FADING_EDGE_MASK;
2524 initializeFadingEdge(a);
2525 }
2526 break;
2527 case R.styleable.View_scrollbarStyle:
2528 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2529 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2530 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2531 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2532 }
2533 break;
2534 case R.styleable.View_isScrollContainer:
2535 setScrollContainer = true;
2536 if (a.getBoolean(attr, false)) {
2537 setScrollContainer(true);
2538 }
2539 break;
2540 case com.android.internal.R.styleable.View_keepScreenOn:
2541 if (a.getBoolean(attr, false)) {
2542 viewFlagValues |= KEEP_SCREEN_ON;
2543 viewFlagMasks |= KEEP_SCREEN_ON;
2544 }
2545 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002546 case R.styleable.View_filterTouchesWhenObscured:
2547 if (a.getBoolean(attr, false)) {
2548 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2549 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2550 }
2551 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 case R.styleable.View_nextFocusLeft:
2553 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2554 break;
2555 case R.styleable.View_nextFocusRight:
2556 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2557 break;
2558 case R.styleable.View_nextFocusUp:
2559 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2560 break;
2561 case R.styleable.View_nextFocusDown:
2562 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2563 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002564 case R.styleable.View_nextFocusForward:
2565 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2566 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 case R.styleable.View_minWidth:
2568 mMinWidth = a.getDimensionPixelSize(attr, 0);
2569 break;
2570 case R.styleable.View_minHeight:
2571 mMinHeight = a.getDimensionPixelSize(attr, 0);
2572 break;
Romain Guy9a817362009-05-01 10:57:14 -07002573 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002574 if (context.isRestricted()) {
Joe Malin32736f02011-01-19 16:14:20 -08002575 throw new IllegalStateException("The android:onClick attribute cannot "
Romain Guy870e09f2009-07-06 16:35:25 -07002576 + "be used within a restricted context");
2577 }
2578
Romain Guy9a817362009-05-01 10:57:14 -07002579 final String handlerName = a.getString(attr);
2580 if (handlerName != null) {
2581 setOnClickListener(new OnClickListener() {
2582 private Method mHandler;
2583
2584 public void onClick(View v) {
2585 if (mHandler == null) {
2586 try {
2587 mHandler = getContext().getClass().getMethod(handlerName,
2588 View.class);
2589 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002590 int id = getId();
2591 String idText = id == NO_ID ? "" : " with id '"
2592 + getContext().getResources().getResourceEntryName(
2593 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002594 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002595 handlerName + "(View) in the activity "
2596 + getContext().getClass() + " for onClick handler"
2597 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002598 }
2599 }
2600
2601 try {
2602 mHandler.invoke(getContext(), View.this);
2603 } catch (IllegalAccessException e) {
2604 throw new IllegalStateException("Could not execute non "
2605 + "public method of the activity", e);
2606 } catch (InvocationTargetException e) {
2607 throw new IllegalStateException("Could not execute "
2608 + "method of the activity", e);
2609 }
2610 }
2611 });
2612 }
2613 break;
Adam Powell637d3372010-08-25 14:37:03 -07002614 case R.styleable.View_overScrollMode:
2615 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2616 break;
Adam Powell20232d02010-12-08 21:08:53 -08002617 case R.styleable.View_verticalScrollbarPosition:
2618 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2619 break;
Romain Guy171c5922011-01-06 10:04:23 -08002620 case R.styleable.View_layerType:
2621 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
2622 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 }
2624 }
2625
Adam Powell637d3372010-08-25 14:37:03 -07002626 setOverScrollMode(overScrollMode);
2627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 if (background != null) {
2629 setBackgroundDrawable(background);
2630 }
2631
2632 if (padding >= 0) {
2633 leftPadding = padding;
2634 topPadding = padding;
2635 rightPadding = padding;
2636 bottomPadding = padding;
2637 }
2638
2639 // If the user specified the padding (either with android:padding or
2640 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2641 // use the default padding or the padding from the background drawable
2642 // (stored at this point in mPadding*)
2643 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2644 topPadding >= 0 ? topPadding : mPaddingTop,
2645 rightPadding >= 0 ? rightPadding : mPaddingRight,
2646 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2647
2648 if (viewFlagMasks != 0) {
2649 setFlags(viewFlagValues, viewFlagMasks);
2650 }
2651
2652 // Needs to be called after mViewFlags is set
2653 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2654 recomputePadding();
2655 }
2656
2657 if (x != 0 || y != 0) {
2658 scrollTo(x, y);
2659 }
2660
Chet Haase73066682010-11-29 15:55:32 -08002661 if (transformSet) {
2662 setTranslationX(tx);
2663 setTranslationY(ty);
2664 setRotation(rotation);
2665 setRotationX(rotationX);
2666 setRotationY(rotationY);
2667 setScaleX(sx);
2668 setScaleY(sy);
2669 }
2670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2672 setScrollContainer(true);
2673 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002674
2675 computeOpaqueFlags();
2676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 a.recycle();
2678 }
2679
2680 /**
2681 * Non-public constructor for use in testing
2682 */
2683 View() {
2684 }
2685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 /**
2687 * <p>
2688 * Initializes the fading edges from a given set of styled attributes. This
2689 * method should be called by subclasses that need fading edges and when an
2690 * instance of these subclasses is created programmatically rather than
2691 * being inflated from XML. This method is automatically called when the XML
2692 * is inflated.
2693 * </p>
2694 *
2695 * @param a the styled attributes set to initialize the fading edges from
2696 */
2697 protected void initializeFadingEdge(TypedArray a) {
2698 initScrollCache();
2699
2700 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2701 R.styleable.View_fadingEdgeLength,
2702 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2703 }
2704
2705 /**
2706 * Returns the size of the vertical faded edges used to indicate that more
2707 * content in this view is visible.
2708 *
2709 * @return The size in pixels of the vertical faded edge or 0 if vertical
2710 * faded edges are not enabled for this view.
2711 * @attr ref android.R.styleable#View_fadingEdgeLength
2712 */
2713 public int getVerticalFadingEdgeLength() {
2714 if (isVerticalFadingEdgeEnabled()) {
2715 ScrollabilityCache cache = mScrollCache;
2716 if (cache != null) {
2717 return cache.fadingEdgeLength;
2718 }
2719 }
2720 return 0;
2721 }
2722
2723 /**
2724 * Set the size of the faded edge used to indicate that more content in this
2725 * view is available. Will not change whether the fading edge is enabled; use
2726 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2727 * to enable the fading edge for the vertical or horizontal fading edges.
2728 *
2729 * @param length The size in pixels of the faded edge used to indicate that more
2730 * content in this view is visible.
2731 */
2732 public void setFadingEdgeLength(int length) {
2733 initScrollCache();
2734 mScrollCache.fadingEdgeLength = length;
2735 }
2736
2737 /**
2738 * Returns the size of the horizontal faded edges used to indicate that more
2739 * content in this view is visible.
2740 *
2741 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2742 * faded edges are not enabled for this view.
2743 * @attr ref android.R.styleable#View_fadingEdgeLength
2744 */
2745 public int getHorizontalFadingEdgeLength() {
2746 if (isHorizontalFadingEdgeEnabled()) {
2747 ScrollabilityCache cache = mScrollCache;
2748 if (cache != null) {
2749 return cache.fadingEdgeLength;
2750 }
2751 }
2752 return 0;
2753 }
2754
2755 /**
2756 * Returns the width of the vertical scrollbar.
2757 *
2758 * @return The width in pixels of the vertical scrollbar or 0 if there
2759 * is no vertical scrollbar.
2760 */
2761 public int getVerticalScrollbarWidth() {
2762 ScrollabilityCache cache = mScrollCache;
2763 if (cache != null) {
2764 ScrollBarDrawable scrollBar = cache.scrollBar;
2765 if (scrollBar != null) {
2766 int size = scrollBar.getSize(true);
2767 if (size <= 0) {
2768 size = cache.scrollBarSize;
2769 }
2770 return size;
2771 }
2772 return 0;
2773 }
2774 return 0;
2775 }
2776
2777 /**
2778 * Returns the height of the horizontal scrollbar.
2779 *
2780 * @return The height in pixels of the horizontal scrollbar or 0 if
2781 * there is no horizontal scrollbar.
2782 */
2783 protected int getHorizontalScrollbarHeight() {
2784 ScrollabilityCache cache = mScrollCache;
2785 if (cache != null) {
2786 ScrollBarDrawable scrollBar = cache.scrollBar;
2787 if (scrollBar != null) {
2788 int size = scrollBar.getSize(false);
2789 if (size <= 0) {
2790 size = cache.scrollBarSize;
2791 }
2792 return size;
2793 }
2794 return 0;
2795 }
2796 return 0;
2797 }
2798
2799 /**
2800 * <p>
2801 * Initializes the scrollbars from a given set of styled attributes. This
2802 * method should be called by subclasses that need scrollbars and when an
2803 * instance of these subclasses is created programmatically rather than
2804 * being inflated from XML. This method is automatically called when the XML
2805 * is inflated.
2806 * </p>
2807 *
2808 * @param a the styled attributes set to initialize the scrollbars from
2809 */
2810 protected void initializeScrollbars(TypedArray a) {
2811 initScrollCache();
2812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 final ScrollabilityCache scrollabilityCache = mScrollCache;
Joe Malin32736f02011-01-19 16:14:20 -08002814
Mike Cleronf116bf82009-09-27 19:14:12 -07002815 if (scrollabilityCache.scrollBar == null) {
2816 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2817 }
Joe Malin32736f02011-01-19 16:14:20 -08002818
Romain Guy8bda2482010-03-02 11:42:11 -08002819 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820
Mike Cleronf116bf82009-09-27 19:14:12 -07002821 if (!fadeScrollbars) {
2822 scrollabilityCache.state = ScrollabilityCache.ON;
2823 }
2824 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Joe Malin32736f02011-01-19 16:14:20 -08002825
2826
Mike Cleronf116bf82009-09-27 19:14:12 -07002827 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2828 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2829 .getScrollBarFadeDuration());
2830 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2831 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2832 ViewConfiguration.getScrollDefaultDelay());
2833
Joe Malin32736f02011-01-19 16:14:20 -08002834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2836 com.android.internal.R.styleable.View_scrollbarSize,
2837 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2838
2839 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2840 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2841
2842 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2843 if (thumb != null) {
2844 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2845 }
2846
2847 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2848 false);
2849 if (alwaysDraw) {
2850 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2851 }
2852
2853 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2854 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2855
2856 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2857 if (thumb != null) {
2858 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2859 }
2860
2861 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2862 false);
2863 if (alwaysDraw) {
2864 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2865 }
2866
2867 // Re-apply user/background padding so that scrollbar(s) get added
2868 recomputePadding();
2869 }
2870
2871 /**
2872 * <p>
2873 * Initalizes the scrollability cache if necessary.
2874 * </p>
2875 */
2876 private void initScrollCache() {
2877 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002878 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 }
2880 }
2881
2882 /**
Adam Powell20232d02010-12-08 21:08:53 -08002883 * Set the position of the vertical scroll bar. Should be one of
2884 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
2885 * {@link #SCROLLBAR_POSITION_RIGHT}.
2886 *
2887 * @param position Where the vertical scroll bar should be positioned.
2888 */
2889 public void setVerticalScrollbarPosition(int position) {
2890 if (mVerticalScrollbarPosition != position) {
2891 mVerticalScrollbarPosition = position;
2892 computeOpaqueFlags();
2893 recomputePadding();
2894 }
2895 }
2896
2897 /**
2898 * @return The position where the vertical scroll bar will show, if applicable.
2899 * @see #setVerticalScrollbarPosition(int)
2900 */
2901 public int getVerticalScrollbarPosition() {
2902 return mVerticalScrollbarPosition;
2903 }
2904
2905 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 * Register a callback to be invoked when focus of this view changed.
2907 *
2908 * @param l The callback that will run.
2909 */
2910 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2911 mOnFocusChangeListener = l;
2912 }
2913
2914 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002915 * Add a listener that will be called when the bounds of the view change due to
2916 * layout processing.
2917 *
2918 * @param listener The listener that will be called when layout bounds change.
2919 */
2920 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2921 if (mOnLayoutChangeListeners == null) {
2922 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2923 }
2924 mOnLayoutChangeListeners.add(listener);
2925 }
2926
2927 /**
2928 * Remove a listener for layout changes.
2929 *
2930 * @param listener The listener for layout bounds change.
2931 */
2932 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2933 if (mOnLayoutChangeListeners == null) {
2934 return;
2935 }
2936 mOnLayoutChangeListeners.remove(listener);
2937 }
2938
2939 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 * Returns the focus-change callback registered for this view.
2941 *
2942 * @return The callback, or null if one is not registered.
2943 */
2944 public OnFocusChangeListener getOnFocusChangeListener() {
2945 return mOnFocusChangeListener;
2946 }
2947
2948 /**
2949 * Register a callback to be invoked when this view is clicked. If this view is not
2950 * clickable, it becomes clickable.
2951 *
2952 * @param l The callback that will run
2953 *
2954 * @see #setClickable(boolean)
2955 */
2956 public void setOnClickListener(OnClickListener l) {
2957 if (!isClickable()) {
2958 setClickable(true);
2959 }
2960 mOnClickListener = l;
2961 }
2962
2963 /**
2964 * Register a callback to be invoked when this view is clicked and held. If this view is not
2965 * long clickable, it becomes long clickable.
2966 *
2967 * @param l The callback that will run
2968 *
2969 * @see #setLongClickable(boolean)
2970 */
2971 public void setOnLongClickListener(OnLongClickListener l) {
2972 if (!isLongClickable()) {
2973 setLongClickable(true);
2974 }
2975 mOnLongClickListener = l;
2976 }
2977
2978 /**
2979 * Register a callback to be invoked when the context menu for this view is
2980 * being built. If this view is not long clickable, it becomes long clickable.
2981 *
2982 * @param l The callback that will run
2983 *
2984 */
2985 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2986 if (!isLongClickable()) {
2987 setLongClickable(true);
2988 }
2989 mOnCreateContextMenuListener = l;
2990 }
2991
2992 /**
2993 * Call this view's OnClickListener, if it is defined.
2994 *
2995 * @return True there was an assigned OnClickListener that was called, false
2996 * otherwise is returned.
2997 */
2998 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002999 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 if (mOnClickListener != null) {
3002 playSoundEffect(SoundEffectConstants.CLICK);
3003 mOnClickListener.onClick(this);
3004 return true;
3005 }
3006
3007 return false;
3008 }
3009
3010 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07003011 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3012 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07003014 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 */
3016 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07003017 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 boolean handled = false;
3020 if (mOnLongClickListener != null) {
3021 handled = mOnLongClickListener.onLongClick(View.this);
3022 }
3023 if (!handled) {
3024 handled = showContextMenu();
3025 }
3026 if (handled) {
3027 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3028 }
3029 return handled;
3030 }
3031
3032 /**
3033 * Bring up the context menu for this view.
3034 *
3035 * @return Whether a context menu was displayed.
3036 */
3037 public boolean showContextMenu() {
3038 return getParent().showContextMenuForChild(this);
3039 }
3040
3041 /**
Adam Powell6e346362010-07-23 10:18:23 -07003042 * Start an action mode.
3043 *
3044 * @param callback Callback that will control the lifecycle of the action mode
3045 * @return The new action mode if it is started, null otherwise
3046 *
3047 * @see ActionMode
3048 */
3049 public ActionMode startActionMode(ActionMode.Callback callback) {
3050 return getParent().startActionModeForChild(this, callback);
3051 }
3052
3053 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 * Register a callback to be invoked when a key is pressed in this view.
3055 * @param l the key listener to attach to this view
3056 */
3057 public void setOnKeyListener(OnKeyListener l) {
3058 mOnKeyListener = l;
3059 }
3060
3061 /**
3062 * Register a callback to be invoked when a touch event is sent to this view.
3063 * @param l the touch listener to attach to this view
3064 */
3065 public void setOnTouchListener(OnTouchListener l) {
3066 mOnTouchListener = l;
3067 }
3068
3069 /**
Joe Malin32736f02011-01-19 16:14:20 -08003070 * Register a drag event listener callback object for this View. The parameter is
3071 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3072 * View, the system calls the
3073 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3074 * @param l An implementation of {@link android.view.View.OnDragListener}.
Chris Tate32affef2010-10-18 15:29:21 -07003075 */
3076 public void setOnDragListener(OnDragListener l) {
3077 mOnDragListener = l;
3078 }
3079
3080 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
3082 *
3083 * Note: this does not check whether this {@link View} should get focus, it just
3084 * gives it focus no matter what. It should only be called internally by framework
3085 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3086 *
3087 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
3088 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
3089 * focus moved when requestFocus() is called. It may not always
3090 * apply, in which case use the default View.FOCUS_DOWN.
3091 * @param previouslyFocusedRect The rectangle of the view that had focus
3092 * prior in this View's coordinate system.
3093 */
3094 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3095 if (DBG) {
3096 System.out.println(this + " requestFocus()");
3097 }
3098
3099 if ((mPrivateFlags & FOCUSED) == 0) {
3100 mPrivateFlags |= FOCUSED;
3101
3102 if (mParent != null) {
3103 mParent.requestChildFocus(this, this);
3104 }
3105
3106 onFocusChanged(true, direction, previouslyFocusedRect);
3107 refreshDrawableState();
3108 }
3109 }
3110
3111 /**
3112 * Request that a rectangle of this view be visible on the screen,
3113 * scrolling if necessary just enough.
3114 *
3115 * <p>A View should call this if it maintains some notion of which part
3116 * of its content is interesting. For example, a text editing view
3117 * should call this when its cursor moves.
3118 *
3119 * @param rectangle The rectangle.
3120 * @return Whether any parent scrolled.
3121 */
3122 public boolean requestRectangleOnScreen(Rect rectangle) {
3123 return requestRectangleOnScreen(rectangle, false);
3124 }
3125
3126 /**
3127 * Request that a rectangle of this view be visible on the screen,
3128 * scrolling if necessary just enough.
3129 *
3130 * <p>A View should call this if it maintains some notion of which part
3131 * of its content is interesting. For example, a text editing view
3132 * should call this when its cursor moves.
3133 *
3134 * <p>When <code>immediate</code> is set to true, scrolling will not be
3135 * animated.
3136 *
3137 * @param rectangle The rectangle.
3138 * @param immediate True to forbid animated scrolling, false otherwise
3139 * @return Whether any parent scrolled.
3140 */
3141 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3142 View child = this;
3143 ViewParent parent = mParent;
3144 boolean scrolled = false;
3145 while (parent != null) {
3146 scrolled |= parent.requestChildRectangleOnScreen(child,
3147 rectangle, immediate);
3148
3149 // offset rect so next call has the rectangle in the
3150 // coordinate system of its direct child.
3151 rectangle.offset(child.getLeft(), child.getTop());
3152 rectangle.offset(-child.getScrollX(), -child.getScrollY());
3153
3154 if (!(parent instanceof View)) {
3155 break;
3156 }
Romain Guy8506ab42009-06-11 17:35:47 -07003157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 child = (View) parent;
3159 parent = child.getParent();
3160 }
3161 return scrolled;
3162 }
3163
3164 /**
3165 * Called when this view wants to give up focus. This will cause
3166 * {@link #onFocusChanged} to be called.
3167 */
3168 public void clearFocus() {
3169 if (DBG) {
3170 System.out.println(this + " clearFocus()");
3171 }
3172
3173 if ((mPrivateFlags & FOCUSED) != 0) {
3174 mPrivateFlags &= ~FOCUSED;
3175
3176 if (mParent != null) {
3177 mParent.clearChildFocus(this);
3178 }
3179
3180 onFocusChanged(false, 0, null);
3181 refreshDrawableState();
3182 }
3183 }
3184
3185 /**
3186 * Called to clear the focus of a view that is about to be removed.
3187 * Doesn't call clearChildFocus, which prevents this view from taking
3188 * focus again before it has been removed from the parent
3189 */
3190 void clearFocusForRemoval() {
3191 if ((mPrivateFlags & FOCUSED) != 0) {
3192 mPrivateFlags &= ~FOCUSED;
3193
3194 onFocusChanged(false, 0, null);
3195 refreshDrawableState();
3196 }
3197 }
3198
3199 /**
3200 * Called internally by the view system when a new view is getting focus.
3201 * This is what clears the old focus.
3202 */
3203 void unFocus() {
3204 if (DBG) {
3205 System.out.println(this + " unFocus()");
3206 }
3207
3208 if ((mPrivateFlags & FOCUSED) != 0) {
3209 mPrivateFlags &= ~FOCUSED;
3210
3211 onFocusChanged(false, 0, null);
3212 refreshDrawableState();
3213 }
3214 }
3215
3216 /**
3217 * Returns true if this view has focus iteself, or is the ancestor of the
3218 * view that has focus.
3219 *
3220 * @return True if this view has or contains focus, false otherwise.
3221 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003222 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 public boolean hasFocus() {
3224 return (mPrivateFlags & FOCUSED) != 0;
3225 }
3226
3227 /**
3228 * Returns true if this view is focusable or if it contains a reachable View
3229 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3230 * is a View whose parents do not block descendants focus.
3231 *
3232 * Only {@link #VISIBLE} views are considered focusable.
3233 *
3234 * @return True if the view is focusable or if the view contains a focusable
3235 * View, false otherwise.
3236 *
3237 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3238 */
3239 public boolean hasFocusable() {
3240 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3241 }
3242
3243 /**
3244 * Called by the view system when the focus state of this view changes.
3245 * When the focus change event is caused by directional navigation, direction
3246 * and previouslyFocusedRect provide insight into where the focus is coming from.
3247 * When overriding, be sure to call up through to the super class so that
3248 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07003249 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 * @param gainFocus True if the View has focus; false otherwise.
3251 * @param direction The direction focus has moved when requestFocus()
3252 * is called to give this view focus. Values are
Jeff Brown4e6319b2010-12-13 10:36:51 -08003253 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3254 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3255 * It may not always apply, in which case use the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256 * @param previouslyFocusedRect The rectangle, in this view's coordinate
3257 * system, of the previously focused view. If applicable, this will be
3258 * passed in as finer grained information about where the focus is coming
3259 * from (in addition to direction). Will be <code>null</code> otherwise.
3260 */
3261 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003262 if (gainFocus) {
3263 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3264 }
3265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 InputMethodManager imm = InputMethodManager.peekInstance();
3267 if (!gainFocus) {
3268 if (isPressed()) {
3269 setPressed(false);
3270 }
3271 if (imm != null && mAttachInfo != null
3272 && mAttachInfo.mHasWindowFocus) {
3273 imm.focusOut(this);
3274 }
Romain Guya2431d02009-04-30 16:30:00 -07003275 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 } else if (imm != null && mAttachInfo != null
3277 && mAttachInfo.mHasWindowFocus) {
3278 imm.focusIn(this);
3279 }
Romain Guy8506ab42009-06-11 17:35:47 -07003280
Romain Guy0fd89bf2011-01-26 15:41:30 -08003281 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 if (mOnFocusChangeListener != null) {
3283 mOnFocusChangeListener.onFocusChange(this, gainFocus);
3284 }
Joe Malin32736f02011-01-19 16:14:20 -08003285
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003286 if (mAttachInfo != null) {
3287 mAttachInfo.mKeyDispatchState.reset(this);
3288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 }
3290
3291 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07003292 * {@inheritDoc}
3293 */
3294 public void sendAccessibilityEvent(int eventType) {
3295 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3296 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3297 }
3298 }
3299
3300 /**
3301 * {@inheritDoc}
3302 */
3303 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
Svetoslav Ganov9cd1eca2011-01-13 14:24:02 -08003304 if (!isShown()) {
3305 return;
3306 }
svetoslavganov75986cf2009-05-14 22:28:01 -07003307 event.setClassName(getClass().getName());
3308 event.setPackageName(getContext().getPackageName());
3309 event.setEnabled(isEnabled());
3310 event.setContentDescription(mContentDescription);
3311
3312 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3313 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3314 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3315 event.setItemCount(focusablesTempList.size());
3316 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3317 focusablesTempList.clear();
3318 }
3319
3320 dispatchPopulateAccessibilityEvent(event);
3321
3322 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
3323 }
3324
3325 /**
3326 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3327 * to be populated.
3328 *
3329 * @param event The event.
3330 *
3331 * @return True if the event population was completed.
3332 */
3333 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3334 return false;
3335 }
3336
3337 /**
3338 * Gets the {@link View} description. It briefly describes the view and is
3339 * primarily used for accessibility support. Set this property to enable
3340 * better accessibility support for your application. This is especially
3341 * true for views that do not have textual representation (For example,
3342 * ImageButton).
3343 *
3344 * @return The content descriptiopn.
3345 *
3346 * @attr ref android.R.styleable#View_contentDescription
3347 */
3348 public CharSequence getContentDescription() {
3349 return mContentDescription;
3350 }
3351
3352 /**
3353 * Sets the {@link View} description. It briefly describes the view and is
3354 * primarily used for accessibility support. Set this property to enable
3355 * better accessibility support for your application. This is especially
3356 * true for views that do not have textual representation (For example,
3357 * ImageButton).
3358 *
3359 * @param contentDescription The content description.
3360 *
3361 * @attr ref android.R.styleable#View_contentDescription
3362 */
3363 public void setContentDescription(CharSequence contentDescription) {
3364 mContentDescription = contentDescription;
3365 }
3366
3367 /**
Romain Guya2431d02009-04-30 16:30:00 -07003368 * Invoked whenever this view loses focus, either by losing window focus or by losing
3369 * focus within its window. This method can be used to clear any state tied to the
3370 * focus. For instance, if a button is held pressed with the trackball and the window
3371 * loses focus, this method can be used to cancel the press.
3372 *
3373 * Subclasses of View overriding this method should always call super.onFocusLost().
3374 *
3375 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07003376 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07003377 *
3378 * @hide pending API council approval
3379 */
3380 protected void onFocusLost() {
3381 resetPressedState();
3382 }
3383
3384 private void resetPressedState() {
3385 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3386 return;
3387 }
3388
3389 if (isPressed()) {
3390 setPressed(false);
3391
3392 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05003393 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003394 }
3395 }
3396 }
3397
3398 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 * Returns true if this view has focus
3400 *
3401 * @return True if this view has focus, false otherwise.
3402 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003403 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 public boolean isFocused() {
3405 return (mPrivateFlags & FOCUSED) != 0;
3406 }
3407
3408 /**
3409 * Find the view in the hierarchy rooted at this view that currently has
3410 * focus.
3411 *
3412 * @return The view that currently has focus, or null if no focused view can
3413 * be found.
3414 */
3415 public View findFocus() {
3416 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3417 }
3418
3419 /**
3420 * Change whether this view is one of the set of scrollable containers in
3421 * its window. This will be used to determine whether the window can
3422 * resize or must pan when a soft input area is open -- scrollable
3423 * containers allow the window to use resize mode since the container
3424 * will appropriately shrink.
3425 */
3426 public void setScrollContainer(boolean isScrollContainer) {
3427 if (isScrollContainer) {
3428 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3429 mAttachInfo.mScrollContainers.add(this);
3430 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3431 }
3432 mPrivateFlags |= SCROLL_CONTAINER;
3433 } else {
3434 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3435 mAttachInfo.mScrollContainers.remove(this);
3436 }
3437 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3438 }
3439 }
3440
3441 /**
3442 * Returns the quality of the drawing cache.
3443 *
3444 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3445 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3446 *
3447 * @see #setDrawingCacheQuality(int)
3448 * @see #setDrawingCacheEnabled(boolean)
3449 * @see #isDrawingCacheEnabled()
3450 *
3451 * @attr ref android.R.styleable#View_drawingCacheQuality
3452 */
3453 public int getDrawingCacheQuality() {
3454 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3455 }
3456
3457 /**
3458 * Set the drawing cache quality of this view. This value is used only when the
3459 * drawing cache is enabled
3460 *
3461 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3462 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3463 *
3464 * @see #getDrawingCacheQuality()
3465 * @see #setDrawingCacheEnabled(boolean)
3466 * @see #isDrawingCacheEnabled()
3467 *
3468 * @attr ref android.R.styleable#View_drawingCacheQuality
3469 */
3470 public void setDrawingCacheQuality(int quality) {
3471 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3472 }
3473
3474 /**
3475 * Returns whether the screen should remain on, corresponding to the current
3476 * value of {@link #KEEP_SCREEN_ON}.
3477 *
3478 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3479 *
3480 * @see #setKeepScreenOn(boolean)
3481 *
3482 * @attr ref android.R.styleable#View_keepScreenOn
3483 */
3484 public boolean getKeepScreenOn() {
3485 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3486 }
3487
3488 /**
3489 * Controls whether the screen should remain on, modifying the
3490 * value of {@link #KEEP_SCREEN_ON}.
3491 *
3492 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3493 *
3494 * @see #getKeepScreenOn()
3495 *
3496 * @attr ref android.R.styleable#View_keepScreenOn
3497 */
3498 public void setKeepScreenOn(boolean keepScreenOn) {
3499 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3500 }
3501
3502 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003503 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3504 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 *
3506 * @attr ref android.R.styleable#View_nextFocusLeft
3507 */
3508 public int getNextFocusLeftId() {
3509 return mNextFocusLeftId;
3510 }
3511
3512 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003513 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3514 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
3515 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 *
3517 * @attr ref android.R.styleable#View_nextFocusLeft
3518 */
3519 public void setNextFocusLeftId(int nextFocusLeftId) {
3520 mNextFocusLeftId = nextFocusLeftId;
3521 }
3522
3523 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003524 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3525 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 *
3527 * @attr ref android.R.styleable#View_nextFocusRight
3528 */
3529 public int getNextFocusRightId() {
3530 return mNextFocusRightId;
3531 }
3532
3533 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003534 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3535 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
3536 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 *
3538 * @attr ref android.R.styleable#View_nextFocusRight
3539 */
3540 public void setNextFocusRightId(int nextFocusRightId) {
3541 mNextFocusRightId = nextFocusRightId;
3542 }
3543
3544 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003545 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3546 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 *
3548 * @attr ref android.R.styleable#View_nextFocusUp
3549 */
3550 public int getNextFocusUpId() {
3551 return mNextFocusUpId;
3552 }
3553
3554 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003555 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3556 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
3557 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 *
3559 * @attr ref android.R.styleable#View_nextFocusUp
3560 */
3561 public void setNextFocusUpId(int nextFocusUpId) {
3562 mNextFocusUpId = nextFocusUpId;
3563 }
3564
3565 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003566 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3567 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 *
3569 * @attr ref android.R.styleable#View_nextFocusDown
3570 */
3571 public int getNextFocusDownId() {
3572 return mNextFocusDownId;
3573 }
3574
3575 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003576 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3577 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
3578 * decide automatically.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 *
3580 * @attr ref android.R.styleable#View_nextFocusDown
3581 */
3582 public void setNextFocusDownId(int nextFocusDownId) {
3583 mNextFocusDownId = nextFocusDownId;
3584 }
3585
3586 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08003587 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3588 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3589 *
3590 * @attr ref android.R.styleable#View_nextFocusForward
3591 */
3592 public int getNextFocusForwardId() {
3593 return mNextFocusForwardId;
3594 }
3595
3596 /**
3597 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3598 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
3599 * decide automatically.
3600 *
3601 * @attr ref android.R.styleable#View_nextFocusForward
3602 */
3603 public void setNextFocusForwardId(int nextFocusForwardId) {
3604 mNextFocusForwardId = nextFocusForwardId;
3605 }
3606
3607 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003608 * Returns the visibility of this view and all of its ancestors
3609 *
3610 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3611 */
3612 public boolean isShown() {
3613 View current = this;
3614 //noinspection ConstantConditions
3615 do {
3616 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3617 return false;
3618 }
3619 ViewParent parent = current.mParent;
3620 if (parent == null) {
3621 return false; // We are not attached to the view root
3622 }
3623 if (!(parent instanceof View)) {
3624 return true;
3625 }
3626 current = (View) parent;
3627 } while (current != null);
3628
3629 return false;
3630 }
3631
3632 /**
3633 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3634 * is set
3635 *
3636 * @param insets Insets for system windows
3637 *
3638 * @return True if this view applied the insets, false otherwise
3639 */
3640 protected boolean fitSystemWindows(Rect insets) {
3641 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3642 mPaddingLeft = insets.left;
3643 mPaddingTop = insets.top;
3644 mPaddingRight = insets.right;
3645 mPaddingBottom = insets.bottom;
3646 requestLayout();
3647 return true;
3648 }
3649 return false;
3650 }
3651
3652 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003653 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3654 * @return True if window has FITS_SYSTEM_WINDOWS set
3655 *
3656 * @hide
3657 */
3658 public boolean isFitsSystemWindowsFlagSet() {
3659 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3660 }
3661
3662 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 * Returns the visibility status for this view.
3664 *
3665 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3666 * @attr ref android.R.styleable#View_visibility
3667 */
3668 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003669 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3670 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3671 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 })
3673 public int getVisibility() {
3674 return mViewFlags & VISIBILITY_MASK;
3675 }
3676
3677 /**
3678 * Set the enabled state of this view.
3679 *
3680 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3681 * @attr ref android.R.styleable#View_visibility
3682 */
3683 @RemotableViewMethod
3684 public void setVisibility(int visibility) {
3685 setFlags(visibility, VISIBILITY_MASK);
3686 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3687 }
3688
3689 /**
3690 * Returns the enabled status for this view. The interpretation of the
3691 * enabled state varies by subclass.
3692 *
3693 * @return True if this view is enabled, false otherwise.
3694 */
3695 @ViewDebug.ExportedProperty
3696 public boolean isEnabled() {
3697 return (mViewFlags & ENABLED_MASK) == ENABLED;
3698 }
3699
3700 /**
3701 * Set the enabled state of this view. The interpretation of the enabled
3702 * state varies by subclass.
3703 *
3704 * @param enabled True if this view is enabled, false otherwise.
3705 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003706 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003708 if (enabled == isEnabled()) return;
3709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3711
3712 /*
3713 * The View most likely has to change its appearance, so refresh
3714 * the drawable state.
3715 */
3716 refreshDrawableState();
3717
3718 // Invalidate too, since the default behavior for views is to be
3719 // be drawn at 50% alpha rather than to change the drawable.
Romain Guy0fd89bf2011-01-26 15:41:30 -08003720 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721 }
3722
3723 /**
3724 * Set whether this view can receive the focus.
3725 *
3726 * Setting this to false will also ensure that this view is not focusable
3727 * in touch mode.
3728 *
3729 * @param focusable If true, this view can receive the focus.
3730 *
3731 * @see #setFocusableInTouchMode(boolean)
3732 * @attr ref android.R.styleable#View_focusable
3733 */
3734 public void setFocusable(boolean focusable) {
3735 if (!focusable) {
3736 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3737 }
3738 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3739 }
3740
3741 /**
3742 * Set whether this view can receive focus while in touch mode.
3743 *
3744 * Setting this to true will also ensure that this view is focusable.
3745 *
3746 * @param focusableInTouchMode If true, this view can receive the focus while
3747 * in touch mode.
3748 *
3749 * @see #setFocusable(boolean)
3750 * @attr ref android.R.styleable#View_focusableInTouchMode
3751 */
3752 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3753 // Focusable in touch mode should always be set before the focusable flag
3754 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3755 // which, in touch mode, will not successfully request focus on this view
3756 // because the focusable in touch mode flag is not set
3757 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3758 if (focusableInTouchMode) {
3759 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3760 }
3761 }
3762
3763 /**
3764 * Set whether this view should have sound effects enabled for events such as
3765 * clicking and touching.
3766 *
3767 * <p>You may wish to disable sound effects for a view if you already play sounds,
3768 * for instance, a dial key that plays dtmf tones.
3769 *
3770 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3771 * @see #isSoundEffectsEnabled()
3772 * @see #playSoundEffect(int)
3773 * @attr ref android.R.styleable#View_soundEffectsEnabled
3774 */
3775 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3776 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3777 }
3778
3779 /**
3780 * @return whether this view should have sound effects enabled for events such as
3781 * clicking and touching.
3782 *
3783 * @see #setSoundEffectsEnabled(boolean)
3784 * @see #playSoundEffect(int)
3785 * @attr ref android.R.styleable#View_soundEffectsEnabled
3786 */
3787 @ViewDebug.ExportedProperty
3788 public boolean isSoundEffectsEnabled() {
3789 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3790 }
3791
3792 /**
3793 * Set whether this view should have haptic feedback for events such as
3794 * long presses.
3795 *
3796 * <p>You may wish to disable haptic feedback if your view already controls
3797 * its own haptic feedback.
3798 *
3799 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3800 * @see #isHapticFeedbackEnabled()
3801 * @see #performHapticFeedback(int)
3802 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3803 */
3804 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3805 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3806 }
3807
3808 /**
3809 * @return whether this view should have haptic feedback enabled for events
3810 * long presses.
3811 *
3812 * @see #setHapticFeedbackEnabled(boolean)
3813 * @see #performHapticFeedback(int)
3814 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3815 */
3816 @ViewDebug.ExportedProperty
3817 public boolean isHapticFeedbackEnabled() {
3818 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3819 }
3820
3821 /**
3822 * If this view doesn't do any drawing on its own, set this flag to
3823 * allow further optimizations. By default, this flag is not set on
3824 * View, but could be set on some View subclasses such as ViewGroup.
3825 *
3826 * Typically, if you override {@link #onDraw} you should clear this flag.
3827 *
3828 * @param willNotDraw whether or not this View draw on its own
3829 */
3830 public void setWillNotDraw(boolean willNotDraw) {
3831 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3832 }
3833
3834 /**
3835 * Returns whether or not this View draws on its own.
3836 *
3837 * @return true if this view has nothing to draw, false otherwise
3838 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003839 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 public boolean willNotDraw() {
3841 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3842 }
3843
3844 /**
3845 * When a View's drawing cache is enabled, drawing is redirected to an
3846 * offscreen bitmap. Some views, like an ImageView, must be able to
3847 * bypass this mechanism if they already draw a single bitmap, to avoid
3848 * unnecessary usage of the memory.
3849 *
3850 * @param willNotCacheDrawing true if this view does not cache its
3851 * drawing, false otherwise
3852 */
3853 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3854 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3855 }
3856
3857 /**
3858 * Returns whether or not this View can cache its drawing or not.
3859 *
3860 * @return true if this view does not cache its drawing, false otherwise
3861 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003862 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 public boolean willNotCacheDrawing() {
3864 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3865 }
3866
3867 /**
3868 * Indicates whether this view reacts to click events or not.
3869 *
3870 * @return true if the view is clickable, false otherwise
3871 *
3872 * @see #setClickable(boolean)
3873 * @attr ref android.R.styleable#View_clickable
3874 */
3875 @ViewDebug.ExportedProperty
3876 public boolean isClickable() {
3877 return (mViewFlags & CLICKABLE) == CLICKABLE;
3878 }
3879
3880 /**
3881 * Enables or disables click events for this view. When a view
3882 * is clickable it will change its state to "pressed" on every click.
3883 * Subclasses should set the view clickable to visually react to
3884 * user's clicks.
3885 *
3886 * @param clickable true to make the view clickable, false otherwise
3887 *
3888 * @see #isClickable()
3889 * @attr ref android.R.styleable#View_clickable
3890 */
3891 public void setClickable(boolean clickable) {
3892 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3893 }
3894
3895 /**
3896 * Indicates whether this view reacts to long click events or not.
3897 *
3898 * @return true if the view is long clickable, false otherwise
3899 *
3900 * @see #setLongClickable(boolean)
3901 * @attr ref android.R.styleable#View_longClickable
3902 */
3903 public boolean isLongClickable() {
3904 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3905 }
3906
3907 /**
3908 * Enables or disables long click events for this view. When a view is long
3909 * clickable it reacts to the user holding down the button for a longer
3910 * duration than a tap. This event can either launch the listener or a
3911 * context menu.
3912 *
3913 * @param longClickable true to make the view long clickable, false otherwise
3914 * @see #isLongClickable()
3915 * @attr ref android.R.styleable#View_longClickable
3916 */
3917 public void setLongClickable(boolean longClickable) {
3918 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3919 }
3920
3921 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003922 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003923 *
3924 * @see #isClickable()
3925 * @see #setClickable(boolean)
3926 *
3927 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3928 * the View's internal state from a previously set "pressed" state.
3929 */
3930 public void setPressed(boolean pressed) {
3931 if (pressed) {
3932 mPrivateFlags |= PRESSED;
3933 } else {
3934 mPrivateFlags &= ~PRESSED;
3935 }
3936 refreshDrawableState();
3937 dispatchSetPressed(pressed);
3938 }
3939
3940 /**
3941 * Dispatch setPressed to all of this View's children.
3942 *
3943 * @see #setPressed(boolean)
3944 *
3945 * @param pressed The new pressed state
3946 */
3947 protected void dispatchSetPressed(boolean pressed) {
3948 }
3949
3950 /**
3951 * Indicates whether the view is currently in pressed state. Unless
3952 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3953 * the pressed state.
3954 *
3955 * @see #setPressed
3956 * @see #isClickable()
3957 * @see #setClickable(boolean)
3958 *
3959 * @return true if the view is currently pressed, false otherwise
3960 */
3961 public boolean isPressed() {
3962 return (mPrivateFlags & PRESSED) == PRESSED;
3963 }
3964
3965 /**
3966 * Indicates whether this view will save its state (that is,
3967 * whether its {@link #onSaveInstanceState} method will be called).
3968 *
3969 * @return Returns true if the view state saving is enabled, else false.
3970 *
3971 * @see #setSaveEnabled(boolean)
3972 * @attr ref android.R.styleable#View_saveEnabled
3973 */
3974 public boolean isSaveEnabled() {
3975 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3976 }
3977
3978 /**
3979 * Controls whether the saving of this view's state is
3980 * enabled (that is, whether its {@link #onSaveInstanceState} method
3981 * will be called). Note that even if freezing is enabled, the
3982 * view still must have an id assigned to it (via {@link #setId setId()})
3983 * for its state to be saved. This flag can only disable the
3984 * saving of this view; any child views may still have their state saved.
3985 *
3986 * @param enabled Set to false to <em>disable</em> state saving, or true
3987 * (the default) to allow it.
3988 *
3989 * @see #isSaveEnabled()
3990 * @see #setId(int)
3991 * @see #onSaveInstanceState()
3992 * @attr ref android.R.styleable#View_saveEnabled
3993 */
3994 public void setSaveEnabled(boolean enabled) {
3995 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3996 }
3997
Jeff Brown85a31762010-09-01 17:01:00 -07003998 /**
3999 * Gets whether the framework should discard touches when the view's
4000 * window is obscured by another visible window.
4001 * Refer to the {@link View} security documentation for more details.
4002 *
4003 * @return True if touch filtering is enabled.
4004 *
4005 * @see #setFilterTouchesWhenObscured(boolean)
4006 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4007 */
4008 @ViewDebug.ExportedProperty
4009 public boolean getFilterTouchesWhenObscured() {
4010 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
4011 }
4012
4013 /**
4014 * Sets whether the framework should discard touches when the view's
4015 * window is obscured by another visible window.
4016 * Refer to the {@link View} security documentation for more details.
4017 *
4018 * @param enabled True if touch filtering should be enabled.
4019 *
4020 * @see #getFilterTouchesWhenObscured
4021 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4022 */
4023 public void setFilterTouchesWhenObscured(boolean enabled) {
4024 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
4025 FILTER_TOUCHES_WHEN_OBSCURED);
4026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027
4028 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004029 * Indicates whether the entire hierarchy under this view will save its
4030 * state when a state saving traversal occurs from its parent. The default
4031 * is true; if false, these views will not be saved unless
4032 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4033 *
4034 * @return Returns true if the view state saving from parent is enabled, else false.
4035 *
4036 * @see #setSaveFromParentEnabled(boolean)
4037 */
4038 public boolean isSaveFromParentEnabled() {
4039 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
4040 }
4041
4042 /**
4043 * Controls whether the entire hierarchy under this view will save its
4044 * state when a state saving traversal occurs from its parent. The default
4045 * is true; if false, these views will not be saved unless
4046 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4047 *
4048 * @param enabled Set to false to <em>disable</em> state saving, or true
4049 * (the default) to allow it.
4050 *
4051 * @see #isSaveFromParentEnabled()
4052 * @see #setId(int)
4053 * @see #onSaveInstanceState()
4054 */
4055 public void setSaveFromParentEnabled(boolean enabled) {
4056 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4057 }
4058
4059
4060 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 * Returns whether this View is able to take focus.
4062 *
4063 * @return True if this view can take focus, or false otherwise.
4064 * @attr ref android.R.styleable#View_focusable
4065 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004066 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 public final boolean isFocusable() {
4068 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4069 }
4070
4071 /**
4072 * When a view is focusable, it may not want to take focus when in touch mode.
4073 * For example, a button would like focus when the user is navigating via a D-pad
4074 * so that the user can click on it, but once the user starts touching the screen,
4075 * the button shouldn't take focus
4076 * @return Whether the view is focusable in touch mode.
4077 * @attr ref android.R.styleable#View_focusableInTouchMode
4078 */
4079 @ViewDebug.ExportedProperty
4080 public final boolean isFocusableInTouchMode() {
4081 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
4082 }
4083
4084 /**
4085 * Find the nearest view in the specified direction that can take focus.
4086 * This does not actually give focus to that view.
4087 *
4088 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4089 *
4090 * @return The nearest focusable in the specified direction, or null if none
4091 * can be found.
4092 */
4093 public View focusSearch(int direction) {
4094 if (mParent != null) {
4095 return mParent.focusSearch(this, direction);
4096 } else {
4097 return null;
4098 }
4099 }
4100
4101 /**
4102 * This method is the last chance for the focused view and its ancestors to
4103 * respond to an arrow key. This is called when the focused view did not
4104 * consume the key internally, nor could the view system find a new view in
4105 * the requested direction to give focus to.
4106 *
4107 * @param focused The currently focused view.
4108 * @param direction The direction focus wants to move. One of FOCUS_UP,
4109 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
4110 * @return True if the this view consumed this unhandled move.
4111 */
4112 public boolean dispatchUnhandledMove(View focused, int direction) {
4113 return false;
4114 }
4115
4116 /**
4117 * If a user manually specified the next view id for a particular direction,
Jeff Brown4e6319b2010-12-13 10:36:51 -08004118 * use the root to look up the view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 * @param root The root view of the hierarchy containing this view.
Jeff Brown4e6319b2010-12-13 10:36:51 -08004120 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
4121 * or FOCUS_BACKWARD.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 * @return The user specified next view, or null if there is none.
4123 */
4124 View findUserSetNextFocus(View root, int direction) {
4125 switch (direction) {
4126 case FOCUS_LEFT:
4127 if (mNextFocusLeftId == View.NO_ID) return null;
4128 return findViewShouldExist(root, mNextFocusLeftId);
4129 case FOCUS_RIGHT:
4130 if (mNextFocusRightId == View.NO_ID) return null;
4131 return findViewShouldExist(root, mNextFocusRightId);
4132 case FOCUS_UP:
4133 if (mNextFocusUpId == View.NO_ID) return null;
4134 return findViewShouldExist(root, mNextFocusUpId);
4135 case FOCUS_DOWN:
4136 if (mNextFocusDownId == View.NO_ID) return null;
4137 return findViewShouldExist(root, mNextFocusDownId);
Jeff Brown4e6319b2010-12-13 10:36:51 -08004138 case FOCUS_FORWARD:
4139 if (mNextFocusForwardId == View.NO_ID) return null;
4140 return findViewShouldExist(root, mNextFocusForwardId);
4141 case FOCUS_BACKWARD: {
4142 final int id = mID;
4143 return root.findViewByPredicate(new Predicate<View>() {
4144 @Override
4145 public boolean apply(View t) {
4146 return t.mNextFocusForwardId == id;
4147 }
4148 });
4149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 }
4151 return null;
4152 }
4153
4154 private static View findViewShouldExist(View root, int childViewId) {
4155 View result = root.findViewById(childViewId);
4156 if (result == null) {
4157 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4158 + "by user for id " + childViewId);
4159 }
4160 return result;
4161 }
4162
4163 /**
4164 * Find and return all focusable views that are descendants of this view,
4165 * possibly including this view if it is focusable itself.
4166 *
4167 * @param direction The direction of the focus
4168 * @return A list of focusable views
4169 */
4170 public ArrayList<View> getFocusables(int direction) {
4171 ArrayList<View> result = new ArrayList<View>(24);
4172 addFocusables(result, direction);
4173 return result;
4174 }
4175
4176 /**
4177 * Add any focusable views that are descendants of this view (possibly
4178 * including this view if it is focusable itself) to views. If we are in touch mode,
4179 * only add views that are also focusable in touch mode.
4180 *
4181 * @param views Focusable views found so far
4182 * @param direction The direction of the focus
4183 */
4184 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07004185 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187
svetoslavganov75986cf2009-05-14 22:28:01 -07004188 /**
4189 * Adds any focusable views that are descendants of this view (possibly
4190 * including this view if it is focusable itself) to views. This method
4191 * adds all focusable views regardless if we are in touch mode or
4192 * only views focusable in touch mode if we are in touch mode depending on
4193 * the focusable mode paramater.
4194 *
4195 * @param views Focusable views found so far or null if all we are interested is
4196 * the number of focusables.
4197 * @param direction The direction of the focus.
4198 * @param focusableMode The type of focusables to be added.
4199 *
4200 * @see #FOCUSABLES_ALL
4201 * @see #FOCUSABLES_TOUCH_MODE
4202 */
4203 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4204 if (!isFocusable()) {
4205 return;
4206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207
svetoslavganov75986cf2009-05-14 22:28:01 -07004208 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4209 isInTouchMode() && !isFocusableInTouchMode()) {
4210 return;
4211 }
4212
4213 if (views != null) {
4214 views.add(this);
4215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 }
4217
4218 /**
4219 * Find and return all touchable views that are descendants of this view,
4220 * possibly including this view if it is touchable itself.
4221 *
4222 * @return A list of touchable views
4223 */
4224 public ArrayList<View> getTouchables() {
4225 ArrayList<View> result = new ArrayList<View>();
4226 addTouchables(result);
4227 return result;
4228 }
4229
4230 /**
4231 * Add any touchable views that are descendants of this view (possibly
4232 * including this view if it is touchable itself) to views.
4233 *
4234 * @param views Touchable views found so far
4235 */
4236 public void addTouchables(ArrayList<View> views) {
4237 final int viewFlags = mViewFlags;
4238
4239 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
4240 && (viewFlags & ENABLED_MASK) == ENABLED) {
4241 views.add(this);
4242 }
4243 }
4244
4245 /**
4246 * Call this to try to give focus to a specific view or to one of its
4247 * descendants.
4248 *
4249 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4250 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4251 * while the device is in touch mode.
4252 *
4253 * See also {@link #focusSearch}, which is what you call to say that you
4254 * have focus, and you want your parent to look for the next one.
4255 *
4256 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4257 * {@link #FOCUS_DOWN} and <code>null</code>.
4258 *
4259 * @return Whether this view or one of its descendants actually took focus.
4260 */
4261 public final boolean requestFocus() {
4262 return requestFocus(View.FOCUS_DOWN);
4263 }
4264
4265
4266 /**
4267 * Call this to try to give focus to a specific view or to one of its
4268 * descendants and give it a hint about what direction focus is heading.
4269 *
4270 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4271 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4272 * while the device is in touch mode.
4273 *
4274 * See also {@link #focusSearch}, which is what you call to say that you
4275 * have focus, and you want your parent to look for the next one.
4276 *
4277 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4278 * <code>null</code> set for the previously focused rectangle.
4279 *
4280 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4281 * @return Whether this view or one of its descendants actually took focus.
4282 */
4283 public final boolean requestFocus(int direction) {
4284 return requestFocus(direction, null);
4285 }
4286
4287 /**
4288 * Call this to try to give focus to a specific view or to one of its descendants
4289 * and give it hints about the direction and a specific rectangle that the focus
4290 * is coming from. The rectangle can help give larger views a finer grained hint
4291 * about where focus is coming from, and therefore, where to show selection, or
4292 * forward focus change internally.
4293 *
4294 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4295 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4296 * while the device is in touch mode.
4297 *
4298 * A View will not take focus if it is not visible.
4299 *
4300 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
4301 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4302 *
4303 * See also {@link #focusSearch}, which is what you call to say that you
4304 * have focus, and you want your parent to look for the next one.
4305 *
4306 * You may wish to override this method if your custom {@link View} has an internal
4307 * {@link View} that it wishes to forward the request to.
4308 *
4309 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4310 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4311 * to give a finer grained hint about where focus is coming from. May be null
4312 * if there is no hint.
4313 * @return Whether this view or one of its descendants actually took focus.
4314 */
4315 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4316 // need to be focusable
4317 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4318 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4319 return false;
4320 }
4321
4322 // need to be focusable in touch mode if in touch mode
4323 if (isInTouchMode() &&
4324 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4325 return false;
4326 }
4327
4328 // need to not have any parents blocking us
4329 if (hasAncestorThatBlocksDescendantFocus()) {
4330 return false;
4331 }
4332
4333 handleFocusGainInternal(direction, previouslyFocusedRect);
4334 return true;
4335 }
4336
Christopher Tate2c095f32010-10-04 14:13:40 -07004337 /** Gets the ViewRoot, or null if not attached. */
4338 /*package*/ ViewRoot getViewRoot() {
4339 View root = getRootView();
4340 return root != null ? (ViewRoot)root.getParent() : null;
4341 }
4342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 /**
4344 * Call this to try to give focus to a specific view or to one of its descendants. This is a
4345 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4346 * touch mode to request focus when they are touched.
4347 *
4348 * @return Whether this view or one of its descendants actually took focus.
4349 *
4350 * @see #isInTouchMode()
4351 *
4352 */
4353 public final boolean requestFocusFromTouch() {
4354 // Leave touch mode if we need to
4355 if (isInTouchMode()) {
Christopher Tate2c095f32010-10-04 14:13:40 -07004356 ViewRoot viewRoot = getViewRoot();
4357 if (viewRoot != null) {
4358 viewRoot.ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 }
4360 }
4361 return requestFocus(View.FOCUS_DOWN);
4362 }
4363
4364 /**
4365 * @return Whether any ancestor of this view blocks descendant focus.
4366 */
4367 private boolean hasAncestorThatBlocksDescendantFocus() {
4368 ViewParent ancestor = mParent;
4369 while (ancestor instanceof ViewGroup) {
4370 final ViewGroup vgAncestor = (ViewGroup) ancestor;
4371 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4372 return true;
4373 } else {
4374 ancestor = vgAncestor.getParent();
4375 }
4376 }
4377 return false;
4378 }
4379
4380 /**
Romain Guya440b002010-02-24 15:57:54 -08004381 * @hide
4382 */
4383 public void dispatchStartTemporaryDetach() {
4384 onStartTemporaryDetach();
4385 }
4386
4387 /**
4388 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004389 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4390 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08004391 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 */
4393 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08004394 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08004395 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08004396 }
4397
4398 /**
4399 * @hide
4400 */
4401 public void dispatchFinishTemporaryDetach() {
4402 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 }
Romain Guy8506ab42009-06-11 17:35:47 -07004404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004405 /**
4406 * Called after {@link #onStartTemporaryDetach} when the container is done
4407 * changing the view.
4408 */
4409 public void onFinishTemporaryDetach() {
4410 }
Romain Guy8506ab42009-06-11 17:35:47 -07004411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004412 /**
4413 * capture information of this view for later analysis: developement only
4414 * check dynamic switch to make sure we only dump view
4415 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4416 */
4417 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004418 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004419 return;
4420 }
4421 ViewDebug.dumpCapturedView(subTag, v);
4422 }
4423
4424 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004425 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4426 * for this view's window. Returns null if the view is not currently attached
4427 * to the window. Normally you will not need to use this directly, but
4428 * just use the standard high-level event callbacks like {@link #onKeyDown}.
4429 */
4430 public KeyEvent.DispatcherState getKeyDispatcherState() {
4431 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4432 }
Joe Malin32736f02011-01-19 16:14:20 -08004433
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004434 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004435 * Dispatch a key event before it is processed by any input method
4436 * associated with the view hierarchy. This can be used to intercept
4437 * key events in special situations before the IME consumes them; a
4438 * typical example would be handling the BACK key to update the application's
4439 * UI instead of allowing the IME to see it and close itself.
4440 *
4441 * @param event The key event to be dispatched.
4442 * @return True if the event was handled, false otherwise.
4443 */
4444 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4445 return onKeyPreIme(event.getKeyCode(), event);
4446 }
4447
4448 /**
4449 * Dispatch a key event to the next view on the focus path. This path runs
4450 * from the top of the view tree down to the currently focused view. If this
4451 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4452 * the next node down the focus path. This method also fires any key
4453 * listeners.
4454 *
4455 * @param event The key event to be dispatched.
4456 * @return True if the event was handled, false otherwise.
4457 */
4458 public boolean dispatchKeyEvent(KeyEvent event) {
4459 // If any attached key listener a first crack at the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004460
Romain Guyf607bdc2010-09-10 19:20:06 -07004461 //noinspection SimplifiableIfStatement,deprecation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004462 if (android.util.Config.LOGV) {
4463 captureViewInfo("captureViewKeyEvent", this);
4464 }
4465
Romain Guyf607bdc2010-09-10 19:20:06 -07004466 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004467 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4468 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4469 return true;
4470 }
4471
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004472 return event.dispatch(this, mAttachInfo != null
4473 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474 }
4475
4476 /**
4477 * Dispatches a key shortcut event.
4478 *
4479 * @param event The key event to be dispatched.
4480 * @return True if the event was handled by the view, false otherwise.
4481 */
4482 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4483 return onKeyShortcut(event.getKeyCode(), event);
4484 }
4485
4486 /**
4487 * Pass the touch screen motion event down to the target view, or this
4488 * view if it is the target.
4489 *
4490 * @param event The motion event to be dispatched.
4491 * @return True if the event was handled by the view, false otherwise.
4492 */
4493 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004494 if (!onFilterTouchEventForSecurity(event)) {
4495 return false;
4496 }
4497
Romain Guyf607bdc2010-09-10 19:20:06 -07004498 //noinspection SimplifiableIfStatement
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4500 mOnTouchListener.onTouch(this, event)) {
4501 return true;
4502 }
4503 return onTouchEvent(event);
4504 }
4505
4506 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004507 * Filter the touch event to apply security policies.
4508 *
4509 * @param event The motion event to be filtered.
4510 * @return True if the event should be dispatched, false if the event should be dropped.
Joe Malin32736f02011-01-19 16:14:20 -08004511 *
Jeff Brown85a31762010-09-01 17:01:00 -07004512 * @see #getFilterTouchesWhenObscured
4513 */
4514 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
Romain Guyf607bdc2010-09-10 19:20:06 -07004515 //noinspection RedundantIfStatement
Jeff Brown85a31762010-09-01 17:01:00 -07004516 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4517 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4518 // Window is obscured, drop this touch.
4519 return false;
4520 }
4521 return true;
4522 }
4523
4524 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 * Pass a trackball motion event down to the focused view.
4526 *
4527 * @param event The motion event to be dispatched.
4528 * @return True if the event was handled by the view, false otherwise.
4529 */
4530 public boolean dispatchTrackballEvent(MotionEvent event) {
4531 //Log.i("view", "view=" + this + ", " + event.toString());
4532 return onTrackballEvent(event);
4533 }
4534
4535 /**
4536 * Called when the window containing this view gains or loses window focus.
4537 * ViewGroups should override to route to their children.
4538 *
4539 * @param hasFocus True if the window containing this view now has focus,
4540 * false otherwise.
4541 */
4542 public void dispatchWindowFocusChanged(boolean hasFocus) {
4543 onWindowFocusChanged(hasFocus);
4544 }
4545
4546 /**
4547 * Called when the window containing this view gains or loses focus. Note
4548 * that this is separate from view focus: to receive key events, both
4549 * your view and its window must have focus. If a window is displayed
4550 * on top of yours that takes input focus, then your own window will lose
4551 * focus but the view focus will remain unchanged.
4552 *
4553 * @param hasWindowFocus True if the window containing this view now has
4554 * focus, false otherwise.
4555 */
4556 public void onWindowFocusChanged(boolean hasWindowFocus) {
4557 InputMethodManager imm = InputMethodManager.peekInstance();
4558 if (!hasWindowFocus) {
4559 if (isPressed()) {
4560 setPressed(false);
4561 }
4562 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4563 imm.focusOut(this);
4564 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004565 removeLongPressCallback();
Tony Wu26edf202010-09-13 19:54:00 +08004566 removeTapCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004567 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4569 imm.focusIn(this);
4570 }
4571 refreshDrawableState();
4572 }
4573
4574 /**
4575 * Returns true if this view is in a window that currently has window focus.
4576 * Note that this is not the same as the view itself having focus.
4577 *
4578 * @return True if this view is in a window that currently has window focus.
4579 */
4580 public boolean hasWindowFocus() {
4581 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4582 }
4583
4584 /**
Adam Powell326d8082009-12-09 15:10:07 -08004585 * Dispatch a view visibility change down the view hierarchy.
4586 * ViewGroups should override to route to their children.
4587 * @param changedView The view whose visibility changed. Could be 'this' or
4588 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004589 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4590 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004591 */
4592 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4593 onVisibilityChanged(changedView, visibility);
4594 }
4595
4596 /**
4597 * Called when the visibility of the view or an ancestor of the view is changed.
4598 * @param changedView The view whose visibility changed. Could be 'this' or
4599 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004600 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4601 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004602 */
4603 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004604 if (visibility == VISIBLE) {
4605 if (mAttachInfo != null) {
4606 initialAwakenScrollBars();
4607 } else {
4608 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4609 }
4610 }
Adam Powell326d8082009-12-09 15:10:07 -08004611 }
4612
4613 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004614 * Dispatch a hint about whether this view is displayed. For instance, when
4615 * a View moves out of the screen, it might receives a display hint indicating
4616 * the view is not displayed. Applications should not <em>rely</em> on this hint
4617 * as there is no guarantee that they will receive one.
Joe Malin32736f02011-01-19 16:14:20 -08004618 *
Romain Guy43c9cdf2010-01-27 13:53:55 -08004619 * @param hint A hint about whether or not this view is displayed:
4620 * {@link #VISIBLE} or {@link #INVISIBLE}.
4621 */
4622 public void dispatchDisplayHint(int hint) {
4623 onDisplayHint(hint);
4624 }
4625
4626 /**
4627 * Gives this view a hint about whether is displayed or not. For instance, when
4628 * a View moves out of the screen, it might receives a display hint indicating
4629 * the view is not displayed. Applications should not <em>rely</em> on this hint
4630 * as there is no guarantee that they will receive one.
Joe Malin32736f02011-01-19 16:14:20 -08004631 *
Romain Guy43c9cdf2010-01-27 13:53:55 -08004632 * @param hint A hint about whether or not this view is displayed:
4633 * {@link #VISIBLE} or {@link #INVISIBLE}.
4634 */
4635 protected void onDisplayHint(int hint) {
4636 }
4637
4638 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004639 * Dispatch a window visibility change down the view hierarchy.
4640 * ViewGroups should override to route to their children.
4641 *
4642 * @param visibility The new visibility of the window.
4643 *
4644 * @see #onWindowVisibilityChanged
4645 */
4646 public void dispatchWindowVisibilityChanged(int visibility) {
4647 onWindowVisibilityChanged(visibility);
4648 }
4649
4650 /**
4651 * Called when the window containing has change its visibility
4652 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4653 * that this tells you whether or not your window is being made visible
4654 * to the window manager; this does <em>not</em> tell you whether or not
4655 * your window is obscured by other windows on the screen, even if it
4656 * is itself visible.
4657 *
4658 * @param visibility The new visibility of the window.
4659 */
4660 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004661 if (visibility == VISIBLE) {
4662 initialAwakenScrollBars();
4663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004664 }
4665
4666 /**
4667 * Returns the current visibility of the window this view is attached to
4668 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4669 *
4670 * @return Returns the current visibility of the view's window.
4671 */
4672 public int getWindowVisibility() {
4673 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4674 }
4675
4676 /**
4677 * Retrieve the overall visible display size in which the window this view is
4678 * attached to has been positioned in. This takes into account screen
4679 * decorations above the window, for both cases where the window itself
4680 * is being position inside of them or the window is being placed under
4681 * then and covered insets are used for the window to position its content
4682 * inside. In effect, this tells you the available area where content can
4683 * be placed and remain visible to users.
4684 *
4685 * <p>This function requires an IPC back to the window manager to retrieve
4686 * the requested information, so should not be used in performance critical
4687 * code like drawing.
4688 *
4689 * @param outRect Filled in with the visible display frame. If the view
4690 * is not attached to a window, this is simply the raw display size.
4691 */
4692 public void getWindowVisibleDisplayFrame(Rect outRect) {
4693 if (mAttachInfo != null) {
4694 try {
4695 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4696 } catch (RemoteException e) {
4697 return;
4698 }
4699 // XXX This is really broken, and probably all needs to be done
4700 // in the window manager, and we need to know more about whether
4701 // we want the area behind or in front of the IME.
4702 final Rect insets = mAttachInfo.mVisibleInsets;
4703 outRect.left += insets.left;
4704 outRect.top += insets.top;
4705 outRect.right -= insets.right;
4706 outRect.bottom -= insets.bottom;
4707 return;
4708 }
4709 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4710 outRect.set(0, 0, d.getWidth(), d.getHeight());
4711 }
4712
4713 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004714 * Dispatch a notification about a resource configuration change down
4715 * the view hierarchy.
4716 * ViewGroups should override to route to their children.
4717 *
4718 * @param newConfig The new resource configuration.
4719 *
4720 * @see #onConfigurationChanged
4721 */
4722 public void dispatchConfigurationChanged(Configuration newConfig) {
4723 onConfigurationChanged(newConfig);
4724 }
4725
4726 /**
4727 * Called when the current configuration of the resources being used
4728 * by the application have changed. You can use this to decide when
4729 * to reload resources that can changed based on orientation and other
4730 * configuration characterstics. You only need to use this if you are
4731 * not relying on the normal {@link android.app.Activity} mechanism of
4732 * recreating the activity instance upon a configuration change.
4733 *
4734 * @param newConfig The new resource configuration.
4735 */
4736 protected void onConfigurationChanged(Configuration newConfig) {
4737 }
4738
4739 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004740 * Private function to aggregate all per-view attributes in to the view
4741 * root.
4742 */
4743 void dispatchCollectViewAttributes(int visibility) {
4744 performCollectViewAttributes(visibility);
4745 }
4746
4747 void performCollectViewAttributes(int visibility) {
Romain Guyd30b36d2011-01-26 10:54:43 -08004748 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
Joe Onorato664644d2011-01-23 17:53:23 -08004749 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
4750 mAttachInfo.mKeepScreenOn = true;
4751 }
4752 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
4753 if (mOnSystemUiVisibilityChangeListener != null) {
4754 mAttachInfo.mHasSystemUiListeners = true;
4755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004756 }
4757 }
4758
4759 void needGlobalAttributesUpdate(boolean force) {
Joe Onorato664644d2011-01-23 17:53:23 -08004760 final AttachInfo ai = mAttachInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004761 if (ai != null) {
Joe Onorato664644d2011-01-23 17:53:23 -08004762 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
4763 || ai.mHasSystemUiListeners) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004764 ai.mRecomputeGlobalAttributes = true;
4765 }
4766 }
4767 }
4768
4769 /**
4770 * Returns whether the device is currently in touch mode. Touch mode is entered
4771 * once the user begins interacting with the device by touch, and affects various
4772 * things like whether focus is always visible to the user.
4773 *
4774 * @return Whether the device is in touch mode.
4775 */
4776 @ViewDebug.ExportedProperty
4777 public boolean isInTouchMode() {
4778 if (mAttachInfo != null) {
4779 return mAttachInfo.mInTouchMode;
4780 } else {
4781 return ViewRoot.isInTouchMode();
4782 }
4783 }
4784
4785 /**
4786 * Returns the context the view is running in, through which it can
4787 * access the current theme, resources, etc.
4788 *
4789 * @return The view's Context.
4790 */
4791 @ViewDebug.CapturedViewProperty
4792 public final Context getContext() {
4793 return mContext;
4794 }
4795
4796 /**
4797 * Handle a key event before it is processed by any input method
4798 * associated with the view hierarchy. This can be used to intercept
4799 * key events in special situations before the IME consumes them; a
4800 * typical example would be handling the BACK key to update the application's
4801 * UI instead of allowing the IME to see it and close itself.
4802 *
4803 * @param keyCode The value in event.getKeyCode().
4804 * @param event Description of the key event.
4805 * @return If you handled the event, return true. If you want to allow the
4806 * event to be handled by the next receiver, return false.
4807 */
4808 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4809 return false;
4810 }
4811
4812 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004813 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
4814 * KeyEvent.Callback.onKeyDown()}: perform press of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004815 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4816 * is released, if the view is enabled and clickable.
4817 *
4818 * @param keyCode A key code that represents the button pressed, from
4819 * {@link android.view.KeyEvent}.
4820 * @param event The KeyEvent object that defines the button action.
4821 */
4822 public boolean onKeyDown(int keyCode, KeyEvent event) {
4823 boolean result = false;
4824
4825 switch (keyCode) {
4826 case KeyEvent.KEYCODE_DPAD_CENTER:
4827 case KeyEvent.KEYCODE_ENTER: {
4828 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4829 return true;
4830 }
4831 // Long clickable items don't necessarily have to be clickable
4832 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4833 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4834 (event.getRepeatCount() == 0)) {
4835 setPressed(true);
4836 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004837 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004838 }
4839 return true;
4840 }
4841 break;
4842 }
4843 }
4844 return result;
4845 }
4846
4847 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004848 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4849 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4850 * the event).
4851 */
4852 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4853 return false;
4854 }
4855
4856 /**
Jeff Brown995e7742010-12-22 16:59:36 -08004857 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
4858 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004859 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4860 * {@link KeyEvent#KEYCODE_ENTER} is released.
4861 *
4862 * @param keyCode A key code that represents the button pressed, from
4863 * {@link android.view.KeyEvent}.
4864 * @param event The KeyEvent object that defines the button action.
4865 */
4866 public boolean onKeyUp(int keyCode, KeyEvent event) {
4867 boolean result = false;
4868
4869 switch (keyCode) {
4870 case KeyEvent.KEYCODE_DPAD_CENTER:
4871 case KeyEvent.KEYCODE_ENTER: {
4872 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4873 return true;
4874 }
4875 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4876 setPressed(false);
4877
4878 if (!mHasPerformedLongPress) {
4879 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004880 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004881
4882 result = performClick();
4883 }
4884 }
4885 break;
4886 }
4887 }
4888 return result;
4889 }
4890
4891 /**
4892 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4893 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4894 * the event).
4895 *
4896 * @param keyCode A key code that represents the button pressed, from
4897 * {@link android.view.KeyEvent}.
4898 * @param repeatCount The number of times the action was made.
4899 * @param event The KeyEvent object that defines the button action.
4900 */
4901 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4902 return false;
4903 }
4904
4905 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08004906 * Called on the focused view when a key shortcut event is not handled.
4907 * Override this method to implement local key shortcuts for the View.
4908 * Key shortcuts can also be implemented by setting the
4909 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004910 *
4911 * @param keyCode The value in event.getKeyCode().
4912 * @param event Description of the key event.
4913 * @return If you handled the event, return true. If you want to allow the
4914 * event to be handled by the next receiver, return false.
4915 */
4916 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4917 return false;
4918 }
4919
4920 /**
4921 * Check whether the called view is a text editor, in which case it
4922 * would make sense to automatically display a soft input window for
4923 * it. Subclasses should override this if they implement
4924 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004925 * a call on that method would return a non-null InputConnection, and
4926 * they are really a first-class editor that the user would normally
4927 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004928 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004929 * <p>The default implementation always returns false. This does
4930 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4931 * will not be called or the user can not otherwise perform edits on your
4932 * view; it is just a hint to the system that this is not the primary
4933 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004934 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004935 * @return Returns true if this view is a text editor, else false.
4936 */
4937 public boolean onCheckIsTextEditor() {
4938 return false;
4939 }
Romain Guy8506ab42009-06-11 17:35:47 -07004940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004941 /**
4942 * Create a new InputConnection for an InputMethod to interact
4943 * with the view. The default implementation returns null, since it doesn't
4944 * support input methods. You can override this to implement such support.
4945 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004946 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004947 * <p>When implementing this, you probably also want to implement
4948 * {@link #onCheckIsTextEditor()} to indicate you will return a
4949 * non-null InputConnection.
4950 *
4951 * @param outAttrs Fill in with attribute information about the connection.
4952 */
4953 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4954 return null;
4955 }
4956
4957 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004958 * Called by the {@link android.view.inputmethod.InputMethodManager}
4959 * when a view who is not the current
4960 * input connection target is trying to make a call on the manager. The
4961 * default implementation returns false; you can override this to return
4962 * true for certain views if you are performing InputConnection proxying
4963 * to them.
4964 * @param view The View that is making the InputMethodManager call.
4965 * @return Return true to allow the call, false to reject.
4966 */
4967 public boolean checkInputConnectionProxy(View view) {
4968 return false;
4969 }
Romain Guy8506ab42009-06-11 17:35:47 -07004970
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004971 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004972 * Show the context menu for this view. It is not safe to hold on to the
4973 * menu after returning from this method.
4974 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004975 * You should normally not overload this method. Overload
4976 * {@link #onCreateContextMenu(ContextMenu)} or define an
4977 * {@link OnCreateContextMenuListener} to add items to the context menu.
4978 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004979 * @param menu The context menu to populate
4980 */
4981 public void createContextMenu(ContextMenu menu) {
4982 ContextMenuInfo menuInfo = getContextMenuInfo();
4983
4984 // Sets the current menu info so all items added to menu will have
4985 // my extra info set.
4986 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4987
4988 onCreateContextMenu(menu);
4989 if (mOnCreateContextMenuListener != null) {
4990 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4991 }
4992
4993 // Clear the extra information so subsequent items that aren't mine don't
4994 // have my extra info.
4995 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4996
4997 if (mParent != null) {
4998 mParent.createContextMenu(menu);
4999 }
5000 }
5001
5002 /**
5003 * Views should implement this if they have extra information to associate
5004 * with the context menu. The return result is supplied as a parameter to
5005 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
5006 * callback.
5007 *
5008 * @return Extra information about the item for which the context menu
5009 * should be shown. This information will vary across different
5010 * subclasses of View.
5011 */
5012 protected ContextMenuInfo getContextMenuInfo() {
5013 return null;
5014 }
5015
5016 /**
5017 * Views should implement this if the view itself is going to add items to
5018 * the context menu.
5019 *
5020 * @param menu the context menu to populate
5021 */
5022 protected void onCreateContextMenu(ContextMenu menu) {
5023 }
5024
5025 /**
5026 * Implement this method to handle trackball motion events. The
5027 * <em>relative</em> movement of the trackball since the last event
5028 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
5029 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
5030 * that a movement of 1 corresponds to the user pressing one DPAD key (so
5031 * they will often be fractional values, representing the more fine-grained
5032 * movement information available from a trackball).
5033 *
5034 * @param event The motion event.
5035 * @return True if the event was handled, false otherwise.
5036 */
5037 public boolean onTrackballEvent(MotionEvent event) {
5038 return false;
5039 }
5040
5041 /**
5042 * Implement this method to handle touch screen motion events.
5043 *
5044 * @param event The motion event.
5045 * @return True if the event was handled, false otherwise.
5046 */
5047 public boolean onTouchEvent(MotionEvent event) {
5048 final int viewFlags = mViewFlags;
5049
5050 if ((viewFlags & ENABLED_MASK) == DISABLED) {
5051 // A disabled view that is clickable still consumes the touch
5052 // events, it just doesn't respond to them.
5053 return (((viewFlags & CLICKABLE) == CLICKABLE ||
5054 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
5055 }
5056
5057 if (mTouchDelegate != null) {
5058 if (mTouchDelegate.onTouchEvent(event)) {
5059 return true;
5060 }
5061 }
5062
5063 if (((viewFlags & CLICKABLE) == CLICKABLE ||
5064 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
5065 switch (event.getAction()) {
5066 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08005067 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
5068 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069 // take focus if we don't have it already and we should in
5070 // touch mode.
5071 boolean focusTaken = false;
5072 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
5073 focusTaken = requestFocus();
5074 }
5075
Dianne Hackbornbe1f6222011-01-20 15:24:28 -08005076 if (prepressed) {
5077 // The button is being released before we actually
5078 // showed it as pressed. Make it show the pressed
5079 // state now (before scheduling the click) to ensure
5080 // the user sees it.
5081 mPrivateFlags |= PRESSED;
5082 refreshDrawableState();
5083 }
Joe Malin32736f02011-01-19 16:14:20 -08005084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005085 if (!mHasPerformedLongPress) {
5086 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05005087 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005088
5089 // Only perform take click actions if we were in the pressed state
5090 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08005091 // Use a Runnable and post this rather than calling
5092 // performClick directly. This lets other visual state
5093 // of the view update before click actions start.
5094 if (mPerformClick == null) {
5095 mPerformClick = new PerformClick();
5096 }
5097 if (!post(mPerformClick)) {
5098 performClick();
5099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005100 }
5101 }
5102
5103 if (mUnsetPressedState == null) {
5104 mUnsetPressedState = new UnsetPressedState();
5105 }
5106
Adam Powelle14579b2009-12-16 18:39:52 -08005107 if (prepressed) {
Adam Powelle14579b2009-12-16 18:39:52 -08005108 postDelayed(mUnsetPressedState,
5109 ViewConfiguration.getPressedStateDuration());
5110 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 // If the post failed, unpress right now
5112 mUnsetPressedState.run();
5113 }
Adam Powelle14579b2009-12-16 18:39:52 -08005114 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005115 }
5116 break;
5117
5118 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08005119 if (mPendingCheckForTap == null) {
5120 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005121 }
Adam Powelle14579b2009-12-16 18:39:52 -08005122 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08005123 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08005124 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 break;
5126
5127 case MotionEvent.ACTION_CANCEL:
5128 mPrivateFlags &= ~PRESSED;
5129 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08005130 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005131 break;
5132
5133 case MotionEvent.ACTION_MOVE:
5134 final int x = (int) event.getX();
5135 final int y = (int) event.getY();
5136
5137 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07005138 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08005140 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005141 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08005142 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05005143 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144
5145 // Need to switch from pressed to not pressed
5146 mPrivateFlags &= ~PRESSED;
5147 refreshDrawableState();
5148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005149 }
5150 break;
5151 }
5152 return true;
5153 }
5154
5155 return false;
5156 }
5157
5158 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05005159 * Remove the longpress detection timer.
5160 */
5161 private void removeLongPressCallback() {
5162 if (mPendingCheckForLongPress != null) {
5163 removeCallbacks(mPendingCheckForLongPress);
5164 }
5165 }
Adam Powell3cb8b632011-01-21 15:34:14 -08005166
5167 /**
5168 * Remove the pending click action
5169 */
5170 private void removePerformClickCallback() {
5171 if (mPerformClick != null) {
5172 removeCallbacks(mPerformClick);
5173 }
5174 }
5175
Adam Powelle14579b2009-12-16 18:39:52 -08005176 /**
Romain Guya440b002010-02-24 15:57:54 -08005177 * Remove the prepress detection timer.
5178 */
5179 private void removeUnsetPressCallback() {
5180 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
5181 setPressed(false);
5182 removeCallbacks(mUnsetPressedState);
5183 }
5184 }
5185
5186 /**
Adam Powelle14579b2009-12-16 18:39:52 -08005187 * Remove the tap detection timer.
5188 */
5189 private void removeTapCallback() {
5190 if (mPendingCheckForTap != null) {
5191 mPrivateFlags &= ~PREPRESSED;
5192 removeCallbacks(mPendingCheckForTap);
5193 }
5194 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05005195
5196 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005197 * Cancels a pending long press. Your subclass can use this if you
5198 * want the context menu to come up if the user presses and holds
5199 * at the same place, but you don't want it to come up if they press
5200 * and then move around enough to cause scrolling.
5201 */
5202 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05005203 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08005204
5205 /*
5206 * The prepressed state handled by the tap callback is a display
5207 * construct, but the tap callback will post a long press callback
5208 * less its own timeout. Remove it here.
5209 */
5210 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005211 }
5212
5213 /**
5214 * Sets the TouchDelegate for this View.
5215 */
5216 public void setTouchDelegate(TouchDelegate delegate) {
5217 mTouchDelegate = delegate;
5218 }
5219
5220 /**
5221 * Gets the TouchDelegate for this View.
5222 */
5223 public TouchDelegate getTouchDelegate() {
5224 return mTouchDelegate;
5225 }
5226
5227 /**
5228 * Set flags controlling behavior of this view.
5229 *
5230 * @param flags Constant indicating the value which should be set
5231 * @param mask Constant indicating the bit range that should be changed
5232 */
5233 void setFlags(int flags, int mask) {
5234 int old = mViewFlags;
5235 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
5236
5237 int changed = mViewFlags ^ old;
5238 if (changed == 0) {
5239 return;
5240 }
5241 int privateFlags = mPrivateFlags;
5242
5243 /* Check if the FOCUSABLE bit has changed */
5244 if (((changed & FOCUSABLE_MASK) != 0) &&
5245 ((privateFlags & HAS_BOUNDS) !=0)) {
5246 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
5247 && ((privateFlags & FOCUSED) != 0)) {
5248 /* Give up focus if we are no longer focusable */
5249 clearFocus();
5250 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
5251 && ((privateFlags & FOCUSED) == 0)) {
5252 /*
5253 * Tell the view system that we are now available to take focus
5254 * if no one else already has it.
5255 */
5256 if (mParent != null) mParent.focusableViewAvailable(this);
5257 }
5258 }
5259
5260 if ((flags & VISIBILITY_MASK) == VISIBLE) {
5261 if ((changed & VISIBILITY_MASK) != 0) {
5262 /*
5263 * If this view is becoming visible, set the DRAWN flag so that
5264 * the next invalidate() will not be skipped.
5265 */
5266 mPrivateFlags |= DRAWN;
5267
5268 needGlobalAttributesUpdate(true);
5269
5270 // a view becoming visible is worth notifying the parent
5271 // about in case nothing has focus. even if this specific view
5272 // isn't focusable, it may contain something that is, so let
5273 // the root view try to give this focus if nothing else does.
5274 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
5275 mParent.focusableViewAvailable(this);
5276 }
5277 }
5278 }
5279
5280 /* Check if the GONE bit has changed */
5281 if ((changed & GONE) != 0) {
5282 needGlobalAttributesUpdate(false);
5283 requestLayout();
Romain Guy0fd89bf2011-01-26 15:41:30 -08005284 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005285
Romain Guyecd80ee2009-12-03 17:13:02 -08005286 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
5287 if (hasFocus()) clearFocus();
5288 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005289 }
5290 if (mAttachInfo != null) {
5291 mAttachInfo.mViewVisibilityChanged = true;
5292 }
5293 }
5294
5295 /* Check if the VISIBLE bit has changed */
5296 if ((changed & INVISIBLE) != 0) {
5297 needGlobalAttributesUpdate(false);
Romain Guy0fd89bf2011-01-26 15:41:30 -08005298 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005299
5300 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
5301 // root view becoming invisible shouldn't clear focus
5302 if (getRootView() != this) {
5303 clearFocus();
5304 }
5305 }
5306 if (mAttachInfo != null) {
5307 mAttachInfo.mViewVisibilityChanged = true;
5308 }
5309 }
5310
Adam Powell326d8082009-12-09 15:10:07 -08005311 if ((changed & VISIBILITY_MASK) != 0) {
Chet Haase5e25c2c2010-09-16 11:15:56 -07005312 if (mParent instanceof ViewGroup) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005313 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
5314 ((View) mParent).invalidate(true);
Chet Haase5e25c2c2010-09-16 11:15:56 -07005315 }
Adam Powell326d8082009-12-09 15:10:07 -08005316 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
5317 }
5318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005319 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
5320 destroyDrawingCache();
5321 }
5322
5323 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
5324 destroyDrawingCache();
5325 mPrivateFlags &= ~DRAWING_CACHE_VALID;
Romain Guy0fd89bf2011-01-26 15:41:30 -08005326 invalidateParentCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 }
5328
5329 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
5330 destroyDrawingCache();
5331 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5332 }
5333
5334 if ((changed & DRAW_MASK) != 0) {
5335 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
5336 if (mBGDrawable != null) {
5337 mPrivateFlags &= ~SKIP_DRAW;
5338 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
5339 } else {
5340 mPrivateFlags |= SKIP_DRAW;
5341 }
5342 } else {
5343 mPrivateFlags &= ~SKIP_DRAW;
5344 }
5345 requestLayout();
Romain Guy0fd89bf2011-01-26 15:41:30 -08005346 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005347 }
5348
5349 if ((changed & KEEP_SCREEN_ON) != 0) {
Joe Onorato664644d2011-01-23 17:53:23 -08005350 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005351 mParent.recomputeViewAttributes(this);
5352 }
5353 }
5354 }
5355
5356 /**
5357 * Change the view's z order in the tree, so it's on top of other sibling
5358 * views
5359 */
5360 public void bringToFront() {
5361 if (mParent != null) {
5362 mParent.bringChildToFront(this);
5363 }
5364 }
5365
5366 /**
5367 * This is called in response to an internal scroll in this view (i.e., the
5368 * view scrolled its own contents). This is typically as a result of
5369 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
5370 * called.
5371 *
5372 * @param l Current horizontal scroll origin.
5373 * @param t Current vertical scroll origin.
5374 * @param oldl Previous horizontal scroll origin.
5375 * @param oldt Previous vertical scroll origin.
5376 */
5377 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5378 mBackgroundSizeChanged = true;
5379
5380 final AttachInfo ai = mAttachInfo;
5381 if (ai != null) {
5382 ai.mViewScrollChanged = true;
5383 }
5384 }
5385
5386 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005387 * Interface definition for a callback to be invoked when the layout bounds of a view
5388 * changes due to layout processing.
5389 */
5390 public interface OnLayoutChangeListener {
5391 /**
5392 * Called when the focus state of a view has changed.
5393 *
5394 * @param v The view whose state has changed.
5395 * @param left The new value of the view's left property.
5396 * @param top The new value of the view's top property.
5397 * @param right The new value of the view's right property.
5398 * @param bottom The new value of the view's bottom property.
5399 * @param oldLeft The previous value of the view's left property.
5400 * @param oldTop The previous value of the view's top property.
5401 * @param oldRight The previous value of the view's right property.
5402 * @param oldBottom The previous value of the view's bottom property.
5403 */
5404 void onLayoutChange(View v, int left, int top, int right, int bottom,
5405 int oldLeft, int oldTop, int oldRight, int oldBottom);
5406 }
5407
5408 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 * This is called during layout when the size of this view has changed. If
5410 * you were just added to the view hierarchy, you're called with the old
5411 * values of 0.
5412 *
5413 * @param w Current width of this view.
5414 * @param h Current height of this view.
5415 * @param oldw Old width of this view.
5416 * @param oldh Old height of this view.
5417 */
5418 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5419 }
5420
5421 /**
5422 * Called by draw to draw the child views. This may be overridden
5423 * by derived classes to gain control just before its children are drawn
5424 * (but after its own view has been drawn).
5425 * @param canvas the canvas on which to draw the view
5426 */
5427 protected void dispatchDraw(Canvas canvas) {
5428 }
5429
5430 /**
5431 * Gets the parent of this view. Note that the parent is a
5432 * ViewParent and not necessarily a View.
5433 *
5434 * @return Parent of this view.
5435 */
5436 public final ViewParent getParent() {
5437 return mParent;
5438 }
5439
5440 /**
5441 * Return the scrolled left position of this view. This is the left edge of
5442 * the displayed part of your view. You do not need to draw any pixels
5443 * farther left, since those are outside of the frame of your view on
5444 * screen.
5445 *
5446 * @return The left edge of the displayed part of your view, in pixels.
5447 */
5448 public final int getScrollX() {
5449 return mScrollX;
5450 }
5451
5452 /**
5453 * Return the scrolled top position of this view. This is the top edge of
5454 * the displayed part of your view. You do not need to draw any pixels above
5455 * it, since those are outside of the frame of your view on screen.
5456 *
5457 * @return The top edge of the displayed part of your view, in pixels.
5458 */
5459 public final int getScrollY() {
5460 return mScrollY;
5461 }
5462
5463 /**
5464 * Return the width of the your view.
5465 *
5466 * @return The width of your view, in pixels.
5467 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005468 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005469 public final int getWidth() {
5470 return mRight - mLeft;
5471 }
5472
5473 /**
5474 * Return the height of your view.
5475 *
5476 * @return The height of your view, in pixels.
5477 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005478 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 public final int getHeight() {
5480 return mBottom - mTop;
5481 }
5482
5483 /**
5484 * Return the visible drawing bounds of your view. Fills in the output
5485 * rectangle with the values from getScrollX(), getScrollY(),
5486 * getWidth(), and getHeight().
5487 *
5488 * @param outRect The (scrolled) drawing bounds of the view.
5489 */
5490 public void getDrawingRect(Rect outRect) {
5491 outRect.left = mScrollX;
5492 outRect.top = mScrollY;
5493 outRect.right = mScrollX + (mRight - mLeft);
5494 outRect.bottom = mScrollY + (mBottom - mTop);
5495 }
5496
5497 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005498 * Like {@link #getMeasuredWidthAndState()}, but only returns the
5499 * raw width component (that is the result is masked by
5500 * {@link #MEASURED_SIZE_MASK}).
5501 *
5502 * @return The raw measured width of this view.
5503 */
5504 public final int getMeasuredWidth() {
5505 return mMeasuredWidth & MEASURED_SIZE_MASK;
5506 }
5507
5508 /**
5509 * Return the full width measurement information for this view as computed
5510 * by the most recent call to {@link #measure}. This result is a bit mask
5511 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 * This should be used during measurement and layout calculations only. Use
5513 * {@link #getWidth()} to see how wide a view is after layout.
5514 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005515 * @return The measured width of this view as a bit mask.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005516 */
Dianne Hackborn189ee182010-12-02 21:48:53 -08005517 public final int getMeasuredWidthAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 return mMeasuredWidth;
5519 }
5520
5521 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005522 * Like {@link #getMeasuredHeightAndState()}, but only returns the
5523 * raw width component (that is the result is masked by
5524 * {@link #MEASURED_SIZE_MASK}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 *
Dianne Hackborn189ee182010-12-02 21:48:53 -08005526 * @return The raw measured height of this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005527 */
5528 public final int getMeasuredHeight() {
Dianne Hackborn189ee182010-12-02 21:48:53 -08005529 return mMeasuredHeight & MEASURED_SIZE_MASK;
5530 }
5531
5532 /**
5533 * Return the full height measurement information for this view as computed
5534 * by the most recent call to {@link #measure}. This result is a bit mask
5535 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
5536 * This should be used during measurement and layout calculations only. Use
5537 * {@link #getHeight()} to see how wide a view is after layout.
5538 *
5539 * @return The measured width of this view as a bit mask.
5540 */
5541 public final int getMeasuredHeightAndState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 return mMeasuredHeight;
5543 }
5544
5545 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -08005546 * Return only the state bits of {@link #getMeasuredWidthAndState()}
5547 * and {@link #getMeasuredHeightAndState()}, combined into one integer.
5548 * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
5549 * and the height component is at the shifted bits
5550 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
5551 */
5552 public final int getMeasuredState() {
5553 return (mMeasuredWidth&MEASURED_STATE_MASK)
5554 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
5555 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
5556 }
5557
5558 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005559 * The transform matrix of this view, which is calculated based on the current
5560 * roation, scale, and pivot properties.
5561 *
5562 * @see #getRotation()
5563 * @see #getScaleX()
5564 * @see #getScaleY()
5565 * @see #getPivotX()
5566 * @see #getPivotY()
5567 * @return The current transform matrix for the view
5568 */
5569 public Matrix getMatrix() {
Jeff Brown86671742010-09-30 20:00:15 -07005570 updateMatrix();
Romain Guy33e72ae2010-07-17 12:40:29 -07005571 return mMatrix;
5572 }
5573
5574 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005575 * Utility function to determine if the value is far enough away from zero to be
5576 * considered non-zero.
5577 * @param value A floating point value to check for zero-ness
5578 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5579 */
5580 private static boolean nonzero(float value) {
5581 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5582 }
5583
5584 /**
Jeff Brown86671742010-09-30 20:00:15 -07005585 * Returns true if the transform matrix is the identity matrix.
5586 * Recomputes the matrix if necessary.
Joe Malin32736f02011-01-19 16:14:20 -08005587 *
Romain Guy33e72ae2010-07-17 12:40:29 -07005588 * @return True if the transform matrix is the identity matrix, false otherwise.
5589 */
Jeff Brown86671742010-09-30 20:00:15 -07005590 final boolean hasIdentityMatrix() {
5591 updateMatrix();
5592 return mMatrixIsIdentity;
5593 }
5594
5595 /**
5596 * Recomputes the transform matrix if necessary.
5597 */
Romain Guy2fe9a8f2010-10-04 20:17:01 -07005598 private void updateMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005599 if (mMatrixDirty) {
5600 // transform-related properties have changed since the last time someone
5601 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005602
5603 // Figure out if we need to update the pivot point
5604 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08005605 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005606 mPrevWidth = mRight - mLeft;
5607 mPrevHeight = mBottom - mTop;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -08005608 mPivotX = mPrevWidth / 2f;
5609 mPivotY = mPrevHeight / 2f;
Chet Haasefd2b0022010-08-06 13:08:56 -07005610 }
5611 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005612 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005613 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5614 mMatrix.setTranslate(mTranslationX, mTranslationY);
5615 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5616 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5617 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005618 if (mCamera == null) {
5619 mCamera = new Camera();
5620 matrix3D = new Matrix();
5621 }
5622 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005623 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005624 mCamera.rotateX(mRotationX);
5625 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005626 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005627 mCamera.getMatrix(matrix3D);
5628 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005629 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005630 mMatrix.postConcat(matrix3D);
5631 mCamera.restore();
5632 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005633 mMatrixDirty = false;
5634 mMatrixIsIdentity = mMatrix.isIdentity();
5635 mInverseMatrixDirty = true;
5636 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005637 }
5638
5639 /**
5640 * Utility method to retrieve the inverse of the current mMatrix property.
5641 * We cache the matrix to avoid recalculating it when transform properties
5642 * have not changed.
5643 *
5644 * @return The inverse of the current matrix of this view.
5645 */
Jeff Brown86671742010-09-30 20:00:15 -07005646 final Matrix getInverseMatrix() {
5647 updateMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005648 if (mInverseMatrixDirty) {
5649 if (mInverseMatrix == null) {
5650 mInverseMatrix = new Matrix();
5651 }
5652 mMatrix.invert(mInverseMatrix);
5653 mInverseMatrixDirty = false;
5654 }
5655 return mInverseMatrix;
5656 }
5657
5658 /**
5659 * The degrees that the view is rotated around the pivot point.
5660 *
5661 * @see #getPivotX()
5662 * @see #getPivotY()
5663 * @return The degrees of rotation.
5664 */
5665 public float getRotation() {
5666 return mRotation;
5667 }
5668
5669 /**
Chet Haase897247b2010-09-09 14:54:47 -07005670 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5671 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005672 *
5673 * @param rotation The degrees of rotation.
5674 * @see #getPivotX()
5675 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005676 *
5677 * @attr ref android.R.styleable#View_rotation
Chet Haasec3aa3612010-06-17 08:50:37 -07005678 */
5679 public void setRotation(float rotation) {
5680 if (mRotation != rotation) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005681 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005682 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005683 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005684 mRotation = rotation;
5685 mMatrixDirty = true;
5686 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005687 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005688 }
5689 }
5690
5691 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005692 * The degrees that the view is rotated around the vertical axis through the pivot point.
5693 *
5694 * @see #getPivotX()
5695 * @see #getPivotY()
5696 * @return The degrees of Y rotation.
5697 */
5698 public float getRotationY() {
5699 return mRotationY;
5700 }
5701
5702 /**
Chet Haase897247b2010-09-09 14:54:47 -07005703 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5704 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5705 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005706 *
5707 * @param rotationY The degrees of Y rotation.
5708 * @see #getPivotX()
5709 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005710 *
5711 * @attr ref android.R.styleable#View_rotationY
Chet Haasefd2b0022010-08-06 13:08:56 -07005712 */
5713 public void setRotationY(float rotationY) {
5714 if (mRotationY != rotationY) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005715 invalidateParentCaches();
Chet Haasefd2b0022010-08-06 13:08:56 -07005716 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005717 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005718 mRotationY = rotationY;
5719 mMatrixDirty = true;
5720 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005721 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005722 }
5723 }
5724
5725 /**
5726 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5727 *
5728 * @see #getPivotX()
5729 * @see #getPivotY()
5730 * @return The degrees of X rotation.
5731 */
5732 public float getRotationX() {
5733 return mRotationX;
5734 }
5735
5736 /**
Chet Haase897247b2010-09-09 14:54:47 -07005737 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5738 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5739 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005740 *
5741 * @param rotationX The degrees of X rotation.
5742 * @see #getPivotX()
5743 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005744 *
5745 * @attr ref android.R.styleable#View_rotationX
Chet Haasefd2b0022010-08-06 13:08:56 -07005746 */
5747 public void setRotationX(float rotationX) {
5748 if (mRotationX != rotationX) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005749 invalidateParentCaches();
Chet Haasefd2b0022010-08-06 13:08:56 -07005750 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005751 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005752 mRotationX = rotationX;
5753 mMatrixDirty = true;
5754 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005755 invalidate(false);
Chet Haasefd2b0022010-08-06 13:08:56 -07005756 }
5757 }
5758
5759 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005760 * The amount that the view is scaled in x around the pivot point, as a proportion of
5761 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5762 *
Joe Onorato93162322010-09-16 15:42:01 -04005763 * <p>By default, this is 1.0f.
5764 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005765 * @see #getPivotX()
5766 * @see #getPivotY()
5767 * @return The scaling factor.
5768 */
5769 public float getScaleX() {
5770 return mScaleX;
5771 }
5772
5773 /**
5774 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5775 * the view's unscaled width. A value of 1 means that no scaling is applied.
5776 *
5777 * @param scaleX The scaling factor.
5778 * @see #getPivotX()
5779 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005780 *
5781 * @attr ref android.R.styleable#View_scaleX
Chet Haasec3aa3612010-06-17 08:50:37 -07005782 */
5783 public void setScaleX(float scaleX) {
5784 if (mScaleX != scaleX) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005785 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005786 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005787 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005788 mScaleX = scaleX;
5789 mMatrixDirty = true;
5790 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005791 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005792 }
5793 }
5794
5795 /**
5796 * The amount that the view is scaled in y around the pivot point, as a proportion of
5797 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5798 *
Joe Onorato93162322010-09-16 15:42:01 -04005799 * <p>By default, this is 1.0f.
5800 *
Chet Haasec3aa3612010-06-17 08:50:37 -07005801 * @see #getPivotX()
5802 * @see #getPivotY()
5803 * @return The scaling factor.
5804 */
5805 public float getScaleY() {
5806 return mScaleY;
5807 }
5808
5809 /**
5810 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5811 * the view's unscaled width. A value of 1 means that no scaling is applied.
5812 *
5813 * @param scaleY The scaling factor.
5814 * @see #getPivotX()
5815 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005816 *
5817 * @attr ref android.R.styleable#View_scaleY
Chet Haasec3aa3612010-06-17 08:50:37 -07005818 */
5819 public void setScaleY(float scaleY) {
5820 if (mScaleY != scaleY) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005821 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005822 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005823 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005824 mScaleY = scaleY;
5825 mMatrixDirty = true;
5826 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005827 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005828 }
5829 }
5830
5831 /**
5832 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5833 * and {@link #setScaleX(float) scaled}.
5834 *
5835 * @see #getRotation()
5836 * @see #getScaleX()
5837 * @see #getScaleY()
5838 * @see #getPivotY()
5839 * @return The x location of the pivot point.
5840 */
5841 public float getPivotX() {
5842 return mPivotX;
5843 }
5844
5845 /**
5846 * Sets the x location of the point around which the view is
5847 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005848 * By default, the pivot point is centered on the object.
5849 * Setting this property disables this behavior and causes the view to use only the
5850 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005851 *
5852 * @param pivotX The x location of the pivot point.
5853 * @see #getRotation()
5854 * @see #getScaleX()
5855 * @see #getScaleY()
5856 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005857 *
5858 * @attr ref android.R.styleable#View_transformPivotX
Chet Haasec3aa3612010-06-17 08:50:37 -07005859 */
5860 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005861 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005862 if (mPivotX != pivotX) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005863 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005864 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005865 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005866 mPivotX = pivotX;
5867 mMatrixDirty = true;
5868 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005869 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005870 }
5871 }
5872
5873 /**
5874 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5875 * and {@link #setScaleY(float) scaled}.
5876 *
5877 * @see #getRotation()
5878 * @see #getScaleX()
5879 * @see #getScaleY()
5880 * @see #getPivotY()
5881 * @return The y location of the pivot point.
5882 */
5883 public float getPivotY() {
5884 return mPivotY;
5885 }
5886
5887 /**
5888 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005889 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5890 * Setting this property disables this behavior and causes the view to use only the
5891 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005892 *
5893 * @param pivotY The y location of the pivot point.
5894 * @see #getRotation()
5895 * @see #getScaleX()
5896 * @see #getScaleY()
5897 * @see #getPivotY()
Chet Haase73066682010-11-29 15:55:32 -08005898 *
5899 * @attr ref android.R.styleable#View_transformPivotY
Chet Haasec3aa3612010-06-17 08:50:37 -07005900 */
5901 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005902 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005903 if (mPivotY != pivotY) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08005904 invalidateParentCaches();
Chet Haasec3aa3612010-06-17 08:50:37 -07005905 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07005906 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005907 mPivotY = pivotY;
5908 mMatrixDirty = true;
5909 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07005910 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07005911 }
5912 }
5913
5914 /**
5915 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5916 * completely transparent and 1 means the view is completely opaque.
5917 *
Joe Onorato93162322010-09-16 15:42:01 -04005918 * <p>By default this is 1.0f.
Chet Haasec3aa3612010-06-17 08:50:37 -07005919 * @return The opacity of the view.
5920 */
5921 public float getAlpha() {
5922 return mAlpha;
5923 }
5924
5925 /**
Romain Guy171c5922011-01-06 10:04:23 -08005926 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5927 * completely transparent and 1 means the view is completely opaque.</p>
Joe Malin32736f02011-01-19 16:14:20 -08005928 *
Romain Guy171c5922011-01-06 10:04:23 -08005929 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
5930 * responsible for applying the opacity itself. Otherwise, calling this method is
5931 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
Joe Malin32736f02011-01-19 16:14:20 -08005932 * setting a hardware layer.</p>
Chet Haasec3aa3612010-06-17 08:50:37 -07005933 *
5934 * @param alpha The opacity of the view.
Chet Haase73066682010-11-29 15:55:32 -08005935 *
Joe Malin32736f02011-01-19 16:14:20 -08005936 * @see #setLayerType(int, android.graphics.Paint)
5937 *
Chet Haase73066682010-11-29 15:55:32 -08005938 * @attr ref android.R.styleable#View_alpha
Chet Haasec3aa3612010-06-17 08:50:37 -07005939 */
5940 public void setAlpha(float alpha) {
5941 mAlpha = alpha;
Romain Guy0fd89bf2011-01-26 15:41:30 -08005942 invalidateParentCaches();
Chet Haaseed032702010-10-01 14:05:54 -07005943 if (onSetAlpha((int) (alpha * 255))) {
Romain Guya3496a92010-10-12 11:53:24 -07005944 mPrivateFlags |= ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005945 // subclass is handling alpha - don't optimize rendering cache invalidation
Romain Guy0fd89bf2011-01-26 15:41:30 -08005946 invalidate(true);
Chet Haaseed032702010-10-01 14:05:54 -07005947 } else {
Romain Guya3496a92010-10-12 11:53:24 -07005948 mPrivateFlags &= ~ALPHA_SET;
Chet Haaseed032702010-10-01 14:05:54 -07005949 invalidate(false);
5950 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005951 }
5952
5953 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005954 * Top position of this view relative to its parent.
5955 *
5956 * @return The top of this view, in pixels.
5957 */
5958 @ViewDebug.CapturedViewProperty
5959 public final int getTop() {
5960 return mTop;
5961 }
5962
5963 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005964 * Sets the top position of this view relative to its parent. This method is meant to be called
5965 * by the layout system and should not generally be called otherwise, because the property
5966 * may be changed at any time by the layout.
5967 *
5968 * @param top The top of this view, in pixels.
5969 */
5970 public final void setTop(int top) {
5971 if (top != mTop) {
Jeff Brown86671742010-09-30 20:00:15 -07005972 updateMatrix();
5973 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07005974 final ViewParent p = mParent;
5975 if (p != null && mAttachInfo != null) {
5976 final Rect r = mAttachInfo.mTmpInvalRect;
5977 int minTop;
5978 int yLoc;
5979 if (top < mTop) {
5980 minTop = top;
5981 yLoc = top - mTop;
5982 } else {
5983 minTop = mTop;
5984 yLoc = 0;
5985 }
5986 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5987 p.invalidateChild(this, r);
5988 }
5989 } else {
5990 // Double-invalidation is necessary to capture view's old and new areas
Romain Guy0fd89bf2011-01-26 15:41:30 -08005991 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07005992 }
5993
Chet Haaseed032702010-10-01 14:05:54 -07005994 int width = mRight - mLeft;
5995 int oldHeight = mBottom - mTop;
5996
Chet Haase21cd1382010-09-01 17:42:29 -07005997 mTop = top;
5998
Chet Haaseed032702010-10-01 14:05:54 -07005999 onSizeChanged(width, mBottom - mTop, width, oldHeight);
6000
Chet Haase21cd1382010-09-01 17:42:29 -07006001 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006002 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6003 // A change in dimension means an auto-centered pivot point changes, too
6004 mMatrixDirty = true;
6005 }
Chet Haase21cd1382010-09-01 17:42:29 -07006006 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Romain Guy0fd89bf2011-01-26 15:41:30 -08006007 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006008 }
Chet Haase55dbb652010-12-21 20:15:08 -08006009 mBackgroundSizeChanged = true;
Chet Haase678e0ad2011-01-25 09:37:18 -08006010 invalidateParentIfNeeded();
Chet Haase21cd1382010-09-01 17:42:29 -07006011 }
6012 }
6013
6014 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 * Bottom position of this view relative to its parent.
6016 *
6017 * @return The bottom of this view, in pixels.
6018 */
6019 @ViewDebug.CapturedViewProperty
6020 public final int getBottom() {
6021 return mBottom;
6022 }
6023
6024 /**
Michael Jurkadab559a2011-01-04 20:31:51 -08006025 * True if this view has changed since the last time being drawn.
6026 *
6027 * @return The dirty state of this view.
6028 */
6029 public boolean isDirty() {
6030 return (mPrivateFlags & DIRTY_MASK) != 0;
6031 }
6032
6033 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006034 * Sets the bottom position of this view relative to its parent. This method is meant to be
6035 * called by the layout system and should not generally be called otherwise, because the
6036 * property may be changed at any time by the layout.
6037 *
6038 * @param bottom The bottom of this view, in pixels.
6039 */
6040 public final void setBottom(int bottom) {
6041 if (bottom != mBottom) {
Jeff Brown86671742010-09-30 20:00:15 -07006042 updateMatrix();
6043 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006044 final ViewParent p = mParent;
6045 if (p != null && mAttachInfo != null) {
6046 final Rect r = mAttachInfo.mTmpInvalRect;
6047 int maxBottom;
6048 if (bottom < mBottom) {
6049 maxBottom = mBottom;
6050 } else {
6051 maxBottom = bottom;
6052 }
6053 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
6054 p.invalidateChild(this, r);
6055 }
6056 } else {
6057 // Double-invalidation is necessary to capture view's old and new areas
Romain Guy0fd89bf2011-01-26 15:41:30 -08006058 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006059 }
6060
Chet Haaseed032702010-10-01 14:05:54 -07006061 int width = mRight - mLeft;
6062 int oldHeight = mBottom - mTop;
6063
Chet Haase21cd1382010-09-01 17:42:29 -07006064 mBottom = bottom;
6065
Chet Haaseed032702010-10-01 14:05:54 -07006066 onSizeChanged(width, mBottom - mTop, width, oldHeight);
6067
Chet Haase21cd1382010-09-01 17:42:29 -07006068 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006069 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6070 // A change in dimension means an auto-centered pivot point changes, too
6071 mMatrixDirty = true;
6072 }
Chet Haase21cd1382010-09-01 17:42:29 -07006073 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Romain Guy0fd89bf2011-01-26 15:41:30 -08006074 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006075 }
Chet Haase55dbb652010-12-21 20:15:08 -08006076 mBackgroundSizeChanged = true;
Chet Haase678e0ad2011-01-25 09:37:18 -08006077 invalidateParentIfNeeded();
Chet Haase21cd1382010-09-01 17:42:29 -07006078 }
6079 }
6080
6081 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 * Left position of this view relative to its parent.
6083 *
6084 * @return The left edge of this view, in pixels.
6085 */
6086 @ViewDebug.CapturedViewProperty
6087 public final int getLeft() {
6088 return mLeft;
6089 }
6090
6091 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006092 * Sets the left position of this view relative to its parent. This method is meant to be called
6093 * by the layout system and should not generally be called otherwise, because the property
6094 * may be changed at any time by the layout.
6095 *
6096 * @param left The bottom of this view, in pixels.
6097 */
6098 public final void setLeft(int left) {
6099 if (left != mLeft) {
Jeff Brown86671742010-09-30 20:00:15 -07006100 updateMatrix();
6101 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006102 final ViewParent p = mParent;
6103 if (p != null && mAttachInfo != null) {
6104 final Rect r = mAttachInfo.mTmpInvalRect;
6105 int minLeft;
6106 int xLoc;
6107 if (left < mLeft) {
6108 minLeft = left;
6109 xLoc = left - mLeft;
6110 } else {
6111 minLeft = mLeft;
6112 xLoc = 0;
6113 }
6114 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
6115 p.invalidateChild(this, r);
6116 }
6117 } else {
6118 // Double-invalidation is necessary to capture view's old and new areas
Romain Guy0fd89bf2011-01-26 15:41:30 -08006119 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006120 }
6121
Chet Haaseed032702010-10-01 14:05:54 -07006122 int oldWidth = mRight - mLeft;
6123 int height = mBottom - mTop;
6124
Chet Haase21cd1382010-09-01 17:42:29 -07006125 mLeft = left;
6126
Chet Haaseed032702010-10-01 14:05:54 -07006127 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6128
Chet Haase21cd1382010-09-01 17:42:29 -07006129 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006130 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6131 // A change in dimension means an auto-centered pivot point changes, too
6132 mMatrixDirty = true;
6133 }
Chet Haase21cd1382010-09-01 17:42:29 -07006134 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Romain Guy0fd89bf2011-01-26 15:41:30 -08006135 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006136 }
Chet Haase55dbb652010-12-21 20:15:08 -08006137 mBackgroundSizeChanged = true;
Chet Haase678e0ad2011-01-25 09:37:18 -08006138 invalidateParentIfNeeded();
Chet Haase21cd1382010-09-01 17:42:29 -07006139 }
6140 }
6141
6142 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 * Right position of this view relative to its parent.
6144 *
6145 * @return The right edge of this view, in pixels.
6146 */
6147 @ViewDebug.CapturedViewProperty
6148 public final int getRight() {
6149 return mRight;
6150 }
6151
6152 /**
Chet Haase21cd1382010-09-01 17:42:29 -07006153 * Sets the right position of this view relative to its parent. This method is meant to be called
6154 * by the layout system and should not generally be called otherwise, because the property
6155 * may be changed at any time by the layout.
6156 *
6157 * @param right The bottom of this view, in pixels.
6158 */
6159 public final void setRight(int right) {
6160 if (right != mRight) {
Jeff Brown86671742010-09-30 20:00:15 -07006161 updateMatrix();
6162 if (mMatrixIsIdentity) {
Chet Haase21cd1382010-09-01 17:42:29 -07006163 final ViewParent p = mParent;
6164 if (p != null && mAttachInfo != null) {
6165 final Rect r = mAttachInfo.mTmpInvalRect;
6166 int maxRight;
6167 if (right < mRight) {
6168 maxRight = mRight;
6169 } else {
6170 maxRight = right;
6171 }
6172 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
6173 p.invalidateChild(this, r);
6174 }
6175 } else {
6176 // Double-invalidation is necessary to capture view's old and new areas
Romain Guy0fd89bf2011-01-26 15:41:30 -08006177 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006178 }
6179
Chet Haaseed032702010-10-01 14:05:54 -07006180 int oldWidth = mRight - mLeft;
6181 int height = mBottom - mTop;
6182
Chet Haase21cd1382010-09-01 17:42:29 -07006183 mRight = right;
6184
Chet Haaseed032702010-10-01 14:05:54 -07006185 onSizeChanged(mRight - mLeft, height, oldWidth, height);
6186
Chet Haase21cd1382010-09-01 17:42:29 -07006187 if (!mMatrixIsIdentity) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08006188 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6189 // A change in dimension means an auto-centered pivot point changes, too
6190 mMatrixDirty = true;
6191 }
Chet Haase21cd1382010-09-01 17:42:29 -07006192 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Romain Guy0fd89bf2011-01-26 15:41:30 -08006193 invalidate(true);
Chet Haase21cd1382010-09-01 17:42:29 -07006194 }
Chet Haase55dbb652010-12-21 20:15:08 -08006195 mBackgroundSizeChanged = true;
Chet Haase678e0ad2011-01-25 09:37:18 -08006196 invalidateParentIfNeeded();
Chet Haase21cd1382010-09-01 17:42:29 -07006197 }
6198 }
6199
6200 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006201 * The visual x position of this view, in pixels. This is equivalent to the
6202 * {@link #setTranslationX(float) translationX} property plus the current
Joe Malin32736f02011-01-19 16:14:20 -08006203 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07006204 *
Chet Haasedf030d22010-07-30 17:22:38 -07006205 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006206 */
Chet Haasedf030d22010-07-30 17:22:38 -07006207 public float getX() {
6208 return mLeft + mTranslationX;
6209 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006210
Chet Haasedf030d22010-07-30 17:22:38 -07006211 /**
6212 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
6213 * {@link #setTranslationX(float) translationX} property to be the difference between
6214 * the x value passed in and the current {@link #getLeft() left} property.
6215 *
6216 * @param x The visual x position of this view, in pixels.
6217 */
6218 public void setX(float x) {
6219 setTranslationX(x - mLeft);
6220 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006221
Chet Haasedf030d22010-07-30 17:22:38 -07006222 /**
6223 * The visual y position of this view, in pixels. This is equivalent to the
6224 * {@link #setTranslationY(float) translationY} property plus the current
6225 * {@link #getTop() top} property.
6226 *
6227 * @return The visual y position of this view, in pixels.
6228 */
6229 public float getY() {
6230 return mTop + mTranslationY;
6231 }
6232
6233 /**
6234 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
6235 * {@link #setTranslationY(float) translationY} property to be the difference between
6236 * the y value passed in and the current {@link #getTop() top} property.
6237 *
6238 * @param y The visual y position of this view, in pixels.
6239 */
6240 public void setY(float y) {
6241 setTranslationY(y - mTop);
6242 }
6243
6244
6245 /**
6246 * The horizontal location of this view relative to its {@link #getLeft() left} position.
6247 * This position is post-layout, in addition to wherever the object's
6248 * layout placed it.
6249 *
6250 * @return The horizontal position of this view relative to its left position, in pixels.
6251 */
6252 public float getTranslationX() {
6253 return mTranslationX;
6254 }
6255
6256 /**
6257 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
6258 * This effectively positions the object post-layout, in addition to wherever the object's
6259 * layout placed it.
6260 *
6261 * @param translationX The horizontal position of this view relative to its left position,
6262 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006263 *
6264 * @attr ref android.R.styleable#View_translationX
Chet Haasedf030d22010-07-30 17:22:38 -07006265 */
6266 public void setTranslationX(float translationX) {
6267 if (mTranslationX != translationX) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08006268 invalidateParentCaches();
Chet Haasedf030d22010-07-30 17:22:38 -07006269 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006270 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006271 mTranslationX = translationX;
6272 mMatrixDirty = true;
6273 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006274 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006275 }
6276 }
6277
6278 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006279 * The horizontal location of this view relative to its {@link #getTop() top} position.
6280 * This position is post-layout, in addition to wherever the object's
6281 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006282 *
Chet Haasedf030d22010-07-30 17:22:38 -07006283 * @return The vertical position of this view relative to its top position,
6284 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07006285 */
Chet Haasedf030d22010-07-30 17:22:38 -07006286 public float getTranslationY() {
6287 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07006288 }
6289
6290 /**
Chet Haasedf030d22010-07-30 17:22:38 -07006291 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
6292 * This effectively positions the object post-layout, in addition to wherever the object's
6293 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07006294 *
Chet Haasedf030d22010-07-30 17:22:38 -07006295 * @param translationY The vertical position of this view relative to its top position,
6296 * in pixels.
Chet Haase73066682010-11-29 15:55:32 -08006297 *
6298 * @attr ref android.R.styleable#View_translationY
Chet Haasec3aa3612010-06-17 08:50:37 -07006299 */
Chet Haasedf030d22010-07-30 17:22:38 -07006300 public void setTranslationY(float translationY) {
6301 if (mTranslationY != translationY) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08006302 invalidateParentCaches();
Chet Haasedf030d22010-07-30 17:22:38 -07006303 // Double-invalidation is necessary to capture view's old and new areas
Chet Haaseed032702010-10-01 14:05:54 -07006304 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006305 mTranslationY = translationY;
6306 mMatrixDirty = true;
6307 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006308 invalidate(false);
Chet Haasedf030d22010-07-30 17:22:38 -07006309 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006310 }
6311
6312 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 * Hit rectangle in parent's coordinates
6314 *
6315 * @param outRect The hit rectangle of the view.
6316 */
6317 public void getHitRect(Rect outRect) {
Jeff Brown86671742010-09-30 20:00:15 -07006318 updateMatrix();
6319 if (mMatrixIsIdentity || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006320 outRect.set(mLeft, mTop, mRight, mBottom);
6321 } else {
6322 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07006323 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Jeff Brown86671742010-09-30 20:00:15 -07006324 mMatrix.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07006325 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
6326 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07006327 }
6328 }
6329
6330 /**
Jeff Brown20e987b2010-08-23 12:01:02 -07006331 * Determines whether the given point, in local coordinates is inside the view.
6332 */
6333 /*package*/ final boolean pointInView(float localX, float localY) {
6334 return localX >= 0 && localX < (mRight - mLeft)
6335 && localY >= 0 && localY < (mBottom - mTop);
6336 }
6337
6338 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07006339 * Utility method to determine whether the given point, in local coordinates,
6340 * is inside the view, where the area of the view is expanded by the slop factor.
6341 * This method is called while processing touch-move events to determine if the event
6342 * is still within the view.
6343 */
6344 private boolean pointInView(float localX, float localY, float slop) {
Jeff Brown20e987b2010-08-23 12:01:02 -07006345 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
Romain Guy33e72ae2010-07-17 12:40:29 -07006346 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 }
6348
6349 /**
6350 * When a view has focus and the user navigates away from it, the next view is searched for
6351 * starting from the rectangle filled in by this method.
6352 *
6353 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
6354 * view maintains some idea of internal selection, such as a cursor, or a selected row
6355 * or column, you should override this method and fill in a more specific rectangle.
6356 *
6357 * @param r The rectangle to fill in, in this view's coordinates.
6358 */
6359 public void getFocusedRect(Rect r) {
6360 getDrawingRect(r);
6361 }
6362
6363 /**
6364 * If some part of this view is not clipped by any of its parents, then
6365 * return that area in r in global (root) coordinates. To convert r to local
6366 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
6367 * -globalOffset.y)) If the view is completely clipped or translated out,
6368 * return false.
6369 *
6370 * @param r If true is returned, r holds the global coordinates of the
6371 * visible portion of this view.
6372 * @param globalOffset If true is returned, globalOffset holds the dx,dy
6373 * between this view and its root. globalOffet may be null.
6374 * @return true if r is non-empty (i.e. part of the view is visible at the
6375 * root level.
6376 */
6377 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
6378 int width = mRight - mLeft;
6379 int height = mBottom - mTop;
6380 if (width > 0 && height > 0) {
6381 r.set(0, 0, width, height);
6382 if (globalOffset != null) {
6383 globalOffset.set(-mScrollX, -mScrollY);
6384 }
6385 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
6386 }
6387 return false;
6388 }
6389
6390 public final boolean getGlobalVisibleRect(Rect r) {
6391 return getGlobalVisibleRect(r, null);
6392 }
6393
6394 public final boolean getLocalVisibleRect(Rect r) {
6395 Point offset = new Point();
6396 if (getGlobalVisibleRect(r, offset)) {
6397 r.offset(-offset.x, -offset.y); // make r local
6398 return true;
6399 }
6400 return false;
6401 }
6402
6403 /**
6404 * Offset this view's vertical location by the specified number of pixels.
6405 *
6406 * @param offset the number of pixels to offset the view by
6407 */
6408 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006409 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006410 updateMatrix();
6411 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006412 final ViewParent p = mParent;
6413 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006414 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006415 int minTop;
6416 int maxBottom;
6417 int yLoc;
6418 if (offset < 0) {
6419 minTop = mTop + offset;
6420 maxBottom = mBottom;
6421 yLoc = offset;
6422 } else {
6423 minTop = mTop;
6424 maxBottom = mBottom + offset;
6425 yLoc = 0;
6426 }
6427 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
6428 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006429 }
6430 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006431 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006432 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006433
Chet Haasec3aa3612010-06-17 08:50:37 -07006434 mTop += offset;
6435 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006436
Chet Haasec3aa3612010-06-17 08:50:37 -07006437 if (!mMatrixIsIdentity) {
6438 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006439 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006440 }
Chet Haase678e0ad2011-01-25 09:37:18 -08006441 invalidateParentIfNeeded();
Chet Haasec3aa3612010-06-17 08:50:37 -07006442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 }
6444
6445 /**
6446 * Offset this view's horizontal location by the specified amount of pixels.
6447 *
6448 * @param offset the numer of pixels to offset the view by
6449 */
6450 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006451 if (offset != 0) {
Jeff Brown86671742010-09-30 20:00:15 -07006452 updateMatrix();
6453 if (mMatrixIsIdentity) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006454 final ViewParent p = mParent;
6455 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07006456 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006457 int minLeft;
6458 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006459 if (offset < 0) {
6460 minLeft = mLeft + offset;
6461 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006462 } else {
6463 minLeft = mLeft;
6464 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07006465 }
Chet Haasec3aa3612010-06-17 08:50:37 -07006466 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07006467 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07006468 }
6469 } else {
Chet Haaseed032702010-10-01 14:05:54 -07006470 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006471 }
Romain Guy33e72ae2010-07-17 12:40:29 -07006472
Chet Haasec3aa3612010-06-17 08:50:37 -07006473 mLeft += offset;
6474 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07006475
Chet Haasec3aa3612010-06-17 08:50:37 -07006476 if (!mMatrixIsIdentity) {
6477 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
Chet Haaseed032702010-10-01 14:05:54 -07006478 invalidate(false);
Chet Haasec3aa3612010-06-17 08:50:37 -07006479 }
Chet Haase678e0ad2011-01-25 09:37:18 -08006480 invalidateParentIfNeeded();
Chet Haasec3aa3612010-06-17 08:50:37 -07006481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 }
6483
6484 /**
6485 * Get the LayoutParams associated with this view. All views should have
6486 * layout parameters. These supply parameters to the <i>parent</i> of this
6487 * view specifying how it should be arranged. There are many subclasses of
6488 * ViewGroup.LayoutParams, and these correspond to the different subclasses
6489 * of ViewGroup that are responsible for arranging their children.
6490 * @return The LayoutParams associated with this view
6491 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07006492 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 public ViewGroup.LayoutParams getLayoutParams() {
6494 return mLayoutParams;
6495 }
6496
6497 /**
6498 * Set the layout parameters associated with this view. These supply
6499 * parameters to the <i>parent</i> of this view specifying how it should be
6500 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6501 * correspond to the different subclasses of ViewGroup that are responsible
6502 * for arranging their children.
6503 *
6504 * @param params the layout parameters for this view
6505 */
6506 public void setLayoutParams(ViewGroup.LayoutParams params) {
6507 if (params == null) {
6508 throw new NullPointerException("params == null");
6509 }
6510 mLayoutParams = params;
6511 requestLayout();
6512 }
6513
6514 /**
6515 * Set the scrolled position of your view. This will cause a call to
6516 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6517 * invalidated.
6518 * @param x the x position to scroll to
6519 * @param y the y position to scroll to
6520 */
6521 public void scrollTo(int x, int y) {
6522 if (mScrollX != x || mScrollY != y) {
6523 int oldX = mScrollX;
6524 int oldY = mScrollY;
6525 mScrollX = x;
6526 mScrollY = y;
Romain Guy0fd89bf2011-01-26 15:41:30 -08006527 invalidateParentCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07006529 if (!awakenScrollBars()) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08006530 invalidate(true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 }
6533 }
6534
6535 /**
6536 * Move the scrolled position of your view. This will cause a call to
6537 * {@link #onScrollChanged(int, int, int, int)} and the view will be
6538 * invalidated.
6539 * @param x the amount of pixels to scroll by horizontally
6540 * @param y the amount of pixels to scroll by vertically
6541 */
6542 public void scrollBy(int x, int y) {
6543 scrollTo(mScrollX + x, mScrollY + y);
6544 }
6545
6546 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006547 * <p>Trigger the scrollbars to draw. When invoked this method starts an
6548 * animation to fade the scrollbars out after a default delay. If a subclass
6549 * provides animated scrolling, the start delay should equal the duration
6550 * of the scrolling animation.</p>
6551 *
6552 * <p>The animation starts only if at least one of the scrollbars is
6553 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6554 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6555 * this method returns true, and false otherwise. If the animation is
6556 * started, this method calls {@link #invalidate()}; in that case the
6557 * caller should not call {@link #invalidate()}.</p>
6558 *
6559 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07006560 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07006561 *
6562 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6563 * and {@link #scrollTo(int, int)}.</p>
6564 *
6565 * @return true if the animation is played, false otherwise
6566 *
6567 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07006568 * @see #scrollBy(int, int)
6569 * @see #scrollTo(int, int)
6570 * @see #isHorizontalScrollBarEnabled()
6571 * @see #isVerticalScrollBarEnabled()
6572 * @see #setHorizontalScrollBarEnabled(boolean)
6573 * @see #setVerticalScrollBarEnabled(boolean)
6574 */
6575 protected boolean awakenScrollBars() {
6576 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07006577 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07006578 }
6579
6580 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07006581 * Trigger the scrollbars to draw.
6582 * This method differs from awakenScrollBars() only in its default duration.
6583 * initialAwakenScrollBars() will show the scroll bars for longer than
6584 * usual to give the user more of a chance to notice them.
6585 *
6586 * @return true if the animation is played, false otherwise.
6587 */
6588 private boolean initialAwakenScrollBars() {
6589 return mScrollCache != null &&
6590 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6591 }
6592
6593 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07006594 * <p>
6595 * Trigger the scrollbars to draw. When invoked this method starts an
6596 * animation to fade the scrollbars out after a fixed delay. If a subclass
6597 * provides animated scrolling, the start delay should equal the duration of
6598 * the scrolling animation.
6599 * </p>
Joe Malin32736f02011-01-19 16:14:20 -08006600 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006601 * <p>
6602 * The animation starts only if at least one of the scrollbars is enabled,
6603 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6604 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6605 * this method returns true, and false otherwise. If the animation is
6606 * started, this method calls {@link #invalidate()}; in that case the caller
6607 * should not call {@link #invalidate()}.
6608 * </p>
Joe Malin32736f02011-01-19 16:14:20 -08006609 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006610 * <p>
6611 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07006612 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07006613 * </p>
Joe Malin32736f02011-01-19 16:14:20 -08006614 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006615 * @param startDelay the delay, in milliseconds, after which the animation
6616 * should start; when the delay is 0, the animation starts
6617 * immediately
6618 * @return true if the animation is played, false otherwise
Joe Malin32736f02011-01-19 16:14:20 -08006619 *
Mike Cleronf116bf82009-09-27 19:14:12 -07006620 * @see #scrollBy(int, int)
6621 * @see #scrollTo(int, int)
6622 * @see #isHorizontalScrollBarEnabled()
6623 * @see #isVerticalScrollBarEnabled()
6624 * @see #setHorizontalScrollBarEnabled(boolean)
6625 * @see #setVerticalScrollBarEnabled(boolean)
6626 */
6627 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07006628 return awakenScrollBars(startDelay, true);
6629 }
Joe Malin32736f02011-01-19 16:14:20 -08006630
Mike Cleron290947b2009-09-29 18:34:32 -07006631 /**
6632 * <p>
6633 * Trigger the scrollbars to draw. When invoked this method starts an
6634 * animation to fade the scrollbars out after a fixed delay. If a subclass
6635 * provides animated scrolling, the start delay should equal the duration of
6636 * the scrolling animation.
6637 * </p>
Joe Malin32736f02011-01-19 16:14:20 -08006638 *
Mike Cleron290947b2009-09-29 18:34:32 -07006639 * <p>
6640 * The animation starts only if at least one of the scrollbars is enabled,
6641 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6642 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6643 * this method returns true, and false otherwise. If the animation is
Joe Malin32736f02011-01-19 16:14:20 -08006644 * started, this method calls {@link #invalidate()} if the invalidate parameter
Mike Cleron290947b2009-09-29 18:34:32 -07006645 * is set to true; in that case the caller
6646 * should not call {@link #invalidate()}.
6647 * </p>
Joe Malin32736f02011-01-19 16:14:20 -08006648 *
Mike Cleron290947b2009-09-29 18:34:32 -07006649 * <p>
6650 * This method should be invoked everytime a subclass directly updates the
6651 * scroll parameters.
6652 * </p>
Joe Malin32736f02011-01-19 16:14:20 -08006653 *
Mike Cleron290947b2009-09-29 18:34:32 -07006654 * @param startDelay the delay, in milliseconds, after which the animation
6655 * should start; when the delay is 0, the animation starts
6656 * immediately
Joe Malin32736f02011-01-19 16:14:20 -08006657 *
Mike Cleron290947b2009-09-29 18:34:32 -07006658 * @param invalidate Wheter this method should call invalidate
Joe Malin32736f02011-01-19 16:14:20 -08006659 *
Mike Cleron290947b2009-09-29 18:34:32 -07006660 * @return true if the animation is played, false otherwise
Joe Malin32736f02011-01-19 16:14:20 -08006661 *
Mike Cleron290947b2009-09-29 18:34:32 -07006662 * @see #scrollBy(int, int)
6663 * @see #scrollTo(int, int)
6664 * @see #isHorizontalScrollBarEnabled()
6665 * @see #isVerticalScrollBarEnabled()
6666 * @see #setHorizontalScrollBarEnabled(boolean)
6667 * @see #setVerticalScrollBarEnabled(boolean)
6668 */
6669 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006670 final ScrollabilityCache scrollCache = mScrollCache;
Joe Malin32736f02011-01-19 16:14:20 -08006671
Mike Cleronf116bf82009-09-27 19:14:12 -07006672 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6673 return false;
6674 }
6675
6676 if (scrollCache.scrollBar == null) {
6677 scrollCache.scrollBar = new ScrollBarDrawable();
6678 }
6679
6680 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6681
Mike Cleron290947b2009-09-29 18:34:32 -07006682 if (invalidate) {
6683 // Invalidate to show the scrollbars
Romain Guy0fd89bf2011-01-26 15:41:30 -08006684 invalidate(true);
Mike Cleron290947b2009-09-29 18:34:32 -07006685 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006686
6687 if (scrollCache.state == ScrollabilityCache.OFF) {
6688 // FIXME: this is copied from WindowManagerService.
6689 // We should get this value from the system when it
6690 // is possible to do so.
6691 final int KEY_REPEAT_FIRST_DELAY = 750;
6692 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6693 }
6694
6695 // Tell mScrollCache when we should start fading. This may
6696 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006697 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006698 scrollCache.fadeStartTime = fadeStartTime;
6699 scrollCache.state = ScrollabilityCache.ON;
6700
6701 // Schedule our fader to run, unscheduling any old ones first
6702 if (mAttachInfo != null) {
6703 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6704 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6705 }
6706
6707 return true;
6708 }
6709
6710 return false;
6711 }
6712
6713 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006714 * Mark the the area defined by dirty as needing to be drawn. If the view is
6715 * visible, {@link #onDraw} will be called at some point in the future.
6716 * This must be called from a UI thread. To call from a non-UI thread, call
6717 * {@link #postInvalidate()}.
6718 *
6719 * WARNING: This method is destructive to dirty.
6720 * @param dirty the rectangle representing the bounds of the dirty region
6721 */
6722 public void invalidate(Rect dirty) {
6723 if (ViewDebug.TRACE_HIERARCHY) {
6724 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6725 }
6726
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006727 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
Chet Haasedaf98e92011-01-10 14:10:36 -08006728 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
6729 (mPrivateFlags & INVALIDATED) != INVALIDATED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 mPrivateFlags &= ~DRAWING_CACHE_VALID;
Chet Haasedaf98e92011-01-10 14:10:36 -08006731 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006732 final ViewParent p = mParent;
6733 final AttachInfo ai = mAttachInfo;
Romain Guy7d7b5492011-01-24 16:33:45 -08006734 //noinspection PointlessBooleanExpression,ConstantConditions
6735 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
6736 if (p != null && ai != null && ai.mHardwareAccelerated) {
6737 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6738 // with a null dirty rect, which tells the ViewRoot to redraw everything
6739 p.invalidateChild(this, null);
6740 return;
6741 }
Romain Guyaf636eb2010-12-09 17:47:21 -08006742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006743 if (p != null && ai != null) {
6744 final int scrollX = mScrollX;
6745 final int scrollY = mScrollY;
6746 final Rect r = ai.mTmpInvalRect;
6747 r.set(dirty.left - scrollX, dirty.top - scrollY,
6748 dirty.right - scrollX, dirty.bottom - scrollY);
6749 mParent.invalidateChild(this, r);
6750 }
6751 }
6752 }
6753
6754 /**
6755 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6756 * The coordinates of the dirty rect are relative to the view.
6757 * If the view is visible, {@link #onDraw} will be called at some point
6758 * in the future. This must be called from a UI thread. To call
6759 * from a non-UI thread, call {@link #postInvalidate()}.
6760 * @param l the left position of the dirty region
6761 * @param t the top position of the dirty region
6762 * @param r the right position of the dirty region
6763 * @param b the bottom position of the dirty region
6764 */
6765 public void invalidate(int l, int t, int r, int b) {
6766 if (ViewDebug.TRACE_HIERARCHY) {
6767 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6768 }
6769
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006770 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
Chet Haasedaf98e92011-01-10 14:10:36 -08006771 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
6772 (mPrivateFlags & INVALIDATED) != INVALIDATED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006773 mPrivateFlags &= ~DRAWING_CACHE_VALID;
Chet Haasedaf98e92011-01-10 14:10:36 -08006774 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 final ViewParent p = mParent;
6776 final AttachInfo ai = mAttachInfo;
Romain Guy7d7b5492011-01-24 16:33:45 -08006777 //noinspection PointlessBooleanExpression,ConstantConditions
6778 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
6779 if (p != null && ai != null && ai.mHardwareAccelerated) {
6780 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6781 // with a null dirty rect, which tells the ViewRoot to redraw everything
6782 p.invalidateChild(this, null);
6783 return;
6784 }
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006786 if (p != null && ai != null && l < r && t < b) {
6787 final int scrollX = mScrollX;
6788 final int scrollY = mScrollY;
6789 final Rect tmpr = ai.mTmpInvalRect;
6790 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6791 p.invalidateChild(this, tmpr);
6792 }
6793 }
6794 }
6795
6796 /**
6797 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6798 * be called at some point in the future. This must be called from a
6799 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6800 */
6801 public void invalidate() {
Chet Haaseed032702010-10-01 14:05:54 -07006802 invalidate(true);
6803 }
Joe Malin32736f02011-01-19 16:14:20 -08006804
Chet Haaseed032702010-10-01 14:05:54 -07006805 /**
6806 * This is where the invalidate() work actually happens. A full invalidate()
6807 * causes the drawing cache to be invalidated, but this function can be called with
6808 * invalidateCache set to false to skip that invalidation step for cases that do not
6809 * need it (for example, a component that remains at the same dimensions with the same
6810 * content).
6811 *
6812 * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6813 * well. This is usually true for a full invalidate, but may be set to false if the
6814 * View's contents or dimensions have not changed.
6815 */
6816 private void invalidate(boolean invalidateCache) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006817 if (ViewDebug.TRACE_HIERARCHY) {
6818 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6819 }
6820
Romain Guy2fe9a8f2010-10-04 20:17:01 -07006821 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
Romain Guyc5d55862011-01-21 19:01:46 -08006822 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
Romain Guy0fd89bf2011-01-26 15:41:30 -08006823 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
6824 mLastIsOpaque = isOpaque();
Chet Haaseed032702010-10-01 14:05:54 -07006825 mPrivateFlags &= ~DRAWN;
6826 if (invalidateCache) {
Chet Haasedaf98e92011-01-10 14:10:36 -08006827 mPrivateFlags |= INVALIDATED;
Chet Haaseed032702010-10-01 14:05:54 -07006828 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006830 final AttachInfo ai = mAttachInfo;
Chet Haase70d4ba12010-10-06 09:46:45 -07006831 final ViewParent p = mParent;
Romain Guy7d7b5492011-01-24 16:33:45 -08006832 //noinspection PointlessBooleanExpression,ConstantConditions
6833 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
6834 if (p != null && ai != null && ai.mHardwareAccelerated) {
6835 // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6836 // with a null dirty rect, which tells the ViewRoot to redraw everything
6837 p.invalidateChild(this, null);
6838 return;
6839 }
Chet Haasef2f7d8f2010-12-03 14:08:14 -08006840 }
Michael Jurkaebefea42010-11-15 16:04:01 -08006841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006842 if (p != null && ai != null) {
6843 final Rect r = ai.mTmpInvalRect;
6844 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6845 // Don't call invalidate -- we don't want to internally scroll
6846 // our own bounds
6847 p.invalidateChild(this, r);
6848 }
6849 }
6850 }
6851
6852 /**
Romain Guy0fd89bf2011-01-26 15:41:30 -08006853 * Used to indicate that the parent of this view should clear its caches. This functionality
Chet Haasedaf98e92011-01-10 14:10:36 -08006854 * is used to force the parent to rebuild its display list (when hardware-accelerated),
6855 * which is necessary when various parent-managed properties of the view change, such as
Romain Guy0fd89bf2011-01-26 15:41:30 -08006856 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
6857 * clears the parent caches and does not causes an invalidate event.
Chet Haasedaf98e92011-01-10 14:10:36 -08006858 *
6859 * @hide
6860 */
Romain Guy0fd89bf2011-01-26 15:41:30 -08006861 protected void invalidateParentCaches() {
6862 if (mParent instanceof View) {
6863 ((View) mParent).mPrivateFlags |= INVALIDATED;
6864 }
6865 }
Joe Malin32736f02011-01-19 16:14:20 -08006866
Romain Guy0fd89bf2011-01-26 15:41:30 -08006867 /**
6868 * Used to indicate that the parent of this view should be invalidated. This functionality
6869 * is used to force the parent to rebuild its display list (when hardware-accelerated),
6870 * which is necessary when various parent-managed properties of the view change, such as
6871 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
6872 * an invalidation event to the parent.
6873 *
6874 * @hide
6875 */
6876 protected void invalidateParentIfNeeded() {
Chet Haasedaf98e92011-01-10 14:10:36 -08006877 if (isHardwareAccelerated() && mParent instanceof View) {
Romain Guy0fd89bf2011-01-26 15:41:30 -08006878 ((View) mParent).invalidate(true);
Chet Haasedaf98e92011-01-10 14:10:36 -08006879 }
6880 }
6881
6882 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006883 * Indicates whether this View is opaque. An opaque View guarantees that it will
6884 * draw all the pixels overlapping its bounds using a fully opaque color.
6885 *
6886 * Subclasses of View should override this method whenever possible to indicate
6887 * whether an instance is opaque. Opaque Views are treated in a special way by
6888 * the View hierarchy, possibly allowing it to perform optimizations during
6889 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006890 *
Romain Guy24443ea2009-05-11 11:56:30 -07006891 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006892 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006893 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006894 public boolean isOpaque() {
Chet Haase70d4ba12010-10-06 09:46:45 -07006895 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6896 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
Romain Guy8f1344f52009-05-15 16:03:59 -07006897 }
6898
Adam Powell20232d02010-12-08 21:08:53 -08006899 /**
6900 * @hide
6901 */
6902 protected void computeOpaqueFlags() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006903 // Opaque if:
6904 // - Has a background
6905 // - Background is opaque
6906 // - Doesn't have scrollbars or scrollbars are inside overlay
6907
6908 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6909 mPrivateFlags |= OPAQUE_BACKGROUND;
6910 } else {
6911 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6912 }
6913
6914 final int flags = mViewFlags;
6915 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6916 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6917 mPrivateFlags |= OPAQUE_SCROLLBARS;
6918 } else {
6919 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6920 }
6921 }
6922
6923 /**
6924 * @hide
6925 */
6926 protected boolean hasOpaqueScrollbars() {
6927 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006928 }
6929
6930 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006931 * @return A handler associated with the thread running the View. This
6932 * handler can be used to pump events in the UI events queue.
6933 */
6934 public Handler getHandler() {
6935 if (mAttachInfo != null) {
6936 return mAttachInfo.mHandler;
6937 }
6938 return null;
6939 }
6940
6941 /**
6942 * Causes the Runnable to be added to the message queue.
6943 * The runnable will be run on the user interface thread.
6944 *
6945 * @param action The Runnable that will be executed.
6946 *
6947 * @return Returns true if the Runnable was successfully placed in to the
6948 * message queue. Returns false on failure, usually because the
6949 * looper processing the message queue is exiting.
6950 */
6951 public boolean post(Runnable action) {
6952 Handler handler;
6953 if (mAttachInfo != null) {
6954 handler = mAttachInfo.mHandler;
6955 } else {
6956 // Assume that post will succeed later
6957 ViewRoot.getRunQueue().post(action);
6958 return true;
6959 }
6960
6961 return handler.post(action);
6962 }
6963
6964 /**
6965 * Causes the Runnable to be added to the message queue, to be run
6966 * after the specified amount of time elapses.
6967 * The runnable will be run on the user interface thread.
6968 *
6969 * @param action The Runnable that will be executed.
6970 * @param delayMillis The delay (in milliseconds) until the Runnable
6971 * will be executed.
6972 *
6973 * @return true if the Runnable was successfully placed in to the
6974 * message queue. Returns false on failure, usually because the
6975 * looper processing the message queue is exiting. Note that a
6976 * result of true does not mean the Runnable will be processed --
6977 * if the looper is quit before the delivery time of the message
6978 * occurs then the message will be dropped.
6979 */
6980 public boolean postDelayed(Runnable action, long delayMillis) {
6981 Handler handler;
6982 if (mAttachInfo != null) {
6983 handler = mAttachInfo.mHandler;
6984 } else {
6985 // Assume that post will succeed later
6986 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6987 return true;
6988 }
6989
6990 return handler.postDelayed(action, delayMillis);
6991 }
6992
6993 /**
6994 * Removes the specified Runnable from the message queue.
6995 *
6996 * @param action The Runnable to remove from the message handling queue
6997 *
6998 * @return true if this view could ask the Handler to remove the Runnable,
6999 * false otherwise. When the returned value is true, the Runnable
7000 * may or may not have been actually removed from the message queue
7001 * (for instance, if the Runnable was not in the queue already.)
7002 */
7003 public boolean removeCallbacks(Runnable action) {
7004 Handler handler;
7005 if (mAttachInfo != null) {
7006 handler = mAttachInfo.mHandler;
7007 } else {
7008 // Assume that post will succeed later
7009 ViewRoot.getRunQueue().removeCallbacks(action);
7010 return true;
7011 }
7012
7013 handler.removeCallbacks(action);
7014 return true;
7015 }
7016
7017 /**
7018 * Cause an invalidate to happen on a subsequent cycle through the event loop.
7019 * Use this to invalidate the View from a non-UI thread.
7020 *
7021 * @see #invalidate()
7022 */
7023 public void postInvalidate() {
7024 postInvalidateDelayed(0);
7025 }
7026
7027 /**
7028 * Cause an invalidate of the specified area to happen on a subsequent cycle
7029 * through the event loop. Use this to invalidate the View from a non-UI thread.
7030 *
7031 * @param left The left coordinate of the rectangle to invalidate.
7032 * @param top The top coordinate of the rectangle to invalidate.
7033 * @param right The right coordinate of the rectangle to invalidate.
7034 * @param bottom The bottom coordinate of the rectangle to invalidate.
7035 *
7036 * @see #invalidate(int, int, int, int)
7037 * @see #invalidate(Rect)
7038 */
7039 public void postInvalidate(int left, int top, int right, int bottom) {
7040 postInvalidateDelayed(0, left, top, right, bottom);
7041 }
7042
7043 /**
7044 * Cause an invalidate to happen on a subsequent cycle through the event
7045 * loop. Waits for the specified amount of time.
7046 *
7047 * @param delayMilliseconds the duration in milliseconds to delay the
7048 * invalidation by
7049 */
7050 public void postInvalidateDelayed(long delayMilliseconds) {
7051 // We try only with the AttachInfo because there's no point in invalidating
7052 // if we are not attached to our window
7053 if (mAttachInfo != null) {
7054 Message msg = Message.obtain();
7055 msg.what = AttachInfo.INVALIDATE_MSG;
7056 msg.obj = this;
7057 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
7058 }
7059 }
7060
7061 /**
7062 * Cause an invalidate of the specified area to happen on a subsequent cycle
7063 * through the event loop. Waits for the specified amount of time.
7064 *
7065 * @param delayMilliseconds the duration in milliseconds to delay the
7066 * invalidation by
7067 * @param left The left coordinate of the rectangle to invalidate.
7068 * @param top The top coordinate of the rectangle to invalidate.
7069 * @param right The right coordinate of the rectangle to invalidate.
7070 * @param bottom The bottom coordinate of the rectangle to invalidate.
7071 */
7072 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
7073 int right, int bottom) {
7074
7075 // We try only with the AttachInfo because there's no point in invalidating
7076 // if we are not attached to our window
7077 if (mAttachInfo != null) {
7078 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
7079 info.target = this;
7080 info.left = left;
7081 info.top = top;
7082 info.right = right;
7083 info.bottom = bottom;
7084
7085 final Message msg = Message.obtain();
7086 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
7087 msg.obj = info;
7088 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
7089 }
7090 }
7091
7092 /**
7093 * Called by a parent to request that a child update its values for mScrollX
7094 * and mScrollY if necessary. This will typically be done if the child is
7095 * animating a scroll using a {@link android.widget.Scroller Scroller}
7096 * object.
7097 */
7098 public void computeScroll() {
7099 }
7100
7101 /**
7102 * <p>Indicate whether the horizontal edges are faded when the view is
7103 * scrolled horizontally.</p>
7104 *
7105 * @return true if the horizontal edges should are faded on scroll, false
7106 * otherwise
7107 *
7108 * @see #setHorizontalFadingEdgeEnabled(boolean)
7109 * @attr ref android.R.styleable#View_fadingEdge
7110 */
7111 public boolean isHorizontalFadingEdgeEnabled() {
7112 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
7113 }
7114
7115 /**
7116 * <p>Define whether the horizontal edges should be faded when this view
7117 * is scrolled horizontally.</p>
7118 *
7119 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
7120 * be faded when the view is scrolled
7121 * horizontally
7122 *
7123 * @see #isHorizontalFadingEdgeEnabled()
7124 * @attr ref android.R.styleable#View_fadingEdge
7125 */
7126 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
7127 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
7128 if (horizontalFadingEdgeEnabled) {
7129 initScrollCache();
7130 }
7131
7132 mViewFlags ^= FADING_EDGE_HORIZONTAL;
7133 }
7134 }
7135
7136 /**
7137 * <p>Indicate whether the vertical edges are faded when the view is
7138 * scrolled horizontally.</p>
7139 *
7140 * @return true if the vertical edges should are faded on scroll, false
7141 * otherwise
7142 *
7143 * @see #setVerticalFadingEdgeEnabled(boolean)
7144 * @attr ref android.R.styleable#View_fadingEdge
7145 */
7146 public boolean isVerticalFadingEdgeEnabled() {
7147 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
7148 }
7149
7150 /**
7151 * <p>Define whether the vertical edges should be faded when this view
7152 * is scrolled vertically.</p>
7153 *
7154 * @param verticalFadingEdgeEnabled true if the vertical edges should
7155 * be faded when the view is scrolled
7156 * vertically
7157 *
7158 * @see #isVerticalFadingEdgeEnabled()
7159 * @attr ref android.R.styleable#View_fadingEdge
7160 */
7161 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
7162 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
7163 if (verticalFadingEdgeEnabled) {
7164 initScrollCache();
7165 }
7166
7167 mViewFlags ^= FADING_EDGE_VERTICAL;
7168 }
7169 }
7170
7171 /**
7172 * Returns the strength, or intensity, of the top faded edge. The strength is
7173 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7174 * returns 0.0 or 1.0 but no value in between.
7175 *
7176 * Subclasses should override this method to provide a smoother fade transition
7177 * when scrolling occurs.
7178 *
7179 * @return the intensity of the top fade as a float between 0.0f and 1.0f
7180 */
7181 protected float getTopFadingEdgeStrength() {
7182 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
7183 }
7184
7185 /**
7186 * Returns the strength, or intensity, of the bottom faded edge. The strength is
7187 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7188 * returns 0.0 or 1.0 but no value in between.
7189 *
7190 * Subclasses should override this method to provide a smoother fade transition
7191 * when scrolling occurs.
7192 *
7193 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
7194 */
7195 protected float getBottomFadingEdgeStrength() {
7196 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
7197 computeVerticalScrollRange() ? 1.0f : 0.0f;
7198 }
7199
7200 /**
7201 * Returns the strength, or intensity, of the left faded edge. The strength is
7202 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7203 * returns 0.0 or 1.0 but no value in between.
7204 *
7205 * Subclasses should override this method to provide a smoother fade transition
7206 * when scrolling occurs.
7207 *
7208 * @return the intensity of the left fade as a float between 0.0f and 1.0f
7209 */
7210 protected float getLeftFadingEdgeStrength() {
7211 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
7212 }
7213
7214 /**
7215 * Returns the strength, or intensity, of the right faded edge. The strength is
7216 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7217 * returns 0.0 or 1.0 but no value in between.
7218 *
7219 * Subclasses should override this method to provide a smoother fade transition
7220 * when scrolling occurs.
7221 *
7222 * @return the intensity of the right fade as a float between 0.0f and 1.0f
7223 */
7224 protected float getRightFadingEdgeStrength() {
7225 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
7226 computeHorizontalScrollRange() ? 1.0f : 0.0f;
7227 }
7228
7229 /**
7230 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
7231 * scrollbar is not drawn by default.</p>
7232 *
7233 * @return true if the horizontal scrollbar should be painted, false
7234 * otherwise
7235 *
7236 * @see #setHorizontalScrollBarEnabled(boolean)
7237 */
7238 public boolean isHorizontalScrollBarEnabled() {
7239 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7240 }
7241
7242 /**
7243 * <p>Define whether the horizontal scrollbar should be drawn or not. The
7244 * scrollbar is not drawn by default.</p>
7245 *
7246 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
7247 * be painted
7248 *
7249 * @see #isHorizontalScrollBarEnabled()
7250 */
7251 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
7252 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
7253 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007254 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 recomputePadding();
7256 }
7257 }
7258
7259 /**
7260 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
7261 * scrollbar is not drawn by default.</p>
7262 *
7263 * @return true if the vertical scrollbar should be painted, false
7264 * otherwise
7265 *
7266 * @see #setVerticalScrollBarEnabled(boolean)
7267 */
7268 public boolean isVerticalScrollBarEnabled() {
7269 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
7270 }
7271
7272 /**
7273 * <p>Define whether the vertical scrollbar should be drawn or not. The
7274 * scrollbar is not drawn by default.</p>
7275 *
7276 * @param verticalScrollBarEnabled true if the vertical scrollbar should
7277 * be painted
7278 *
7279 * @see #isVerticalScrollBarEnabled()
7280 */
7281 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
7282 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
7283 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07007284 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007285 recomputePadding();
7286 }
7287 }
7288
Adam Powell20232d02010-12-08 21:08:53 -08007289 /**
7290 * @hide
7291 */
7292 protected void recomputePadding() {
7293 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007294 }
Joe Malin32736f02011-01-19 16:14:20 -08007295
Mike Cleronfe81d382009-09-28 14:22:16 -07007296 /**
7297 * Define whether scrollbars will fade when the view is not scrolling.
Joe Malin32736f02011-01-19 16:14:20 -08007298 *
Mike Cleronfe81d382009-09-28 14:22:16 -07007299 * @param fadeScrollbars wheter to enable fading
Joe Malin32736f02011-01-19 16:14:20 -08007300 *
Mike Cleronfe81d382009-09-28 14:22:16 -07007301 */
7302 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
7303 initScrollCache();
7304 final ScrollabilityCache scrollabilityCache = mScrollCache;
7305 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07007306 if (fadeScrollbars) {
7307 scrollabilityCache.state = ScrollabilityCache.OFF;
7308 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07007309 scrollabilityCache.state = ScrollabilityCache.ON;
7310 }
7311 }
Joe Malin32736f02011-01-19 16:14:20 -08007312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007313 /**
Joe Malin32736f02011-01-19 16:14:20 -08007314 *
Mike Cleron52f0a642009-09-28 18:21:37 -07007315 * Returns true if scrollbars will fade when this view is not scrolling
Joe Malin32736f02011-01-19 16:14:20 -08007316 *
Mike Cleron52f0a642009-09-28 18:21:37 -07007317 * @return true if scrollbar fading is enabled
7318 */
7319 public boolean isScrollbarFadingEnabled() {
Joe Malin32736f02011-01-19 16:14:20 -08007320 return mScrollCache != null && mScrollCache.fadeScrollBars;
Mike Cleron52f0a642009-09-28 18:21:37 -07007321 }
Joe Malin32736f02011-01-19 16:14:20 -08007322
Mike Cleron52f0a642009-09-28 18:21:37 -07007323 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007324 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
7325 * inset. When inset, they add to the padding of the view. And the scrollbars
7326 * can be drawn inside the padding area or on the edge of the view. For example,
7327 * if a view has a background drawable and you want to draw the scrollbars
7328 * inside the padding specified by the drawable, you can use
7329 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
7330 * appear at the edge of the view, ignoring the padding, then you can use
7331 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
7332 * @param style the style of the scrollbars. Should be one of
7333 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
7334 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
7335 * @see #SCROLLBARS_INSIDE_OVERLAY
7336 * @see #SCROLLBARS_INSIDE_INSET
7337 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7338 * @see #SCROLLBARS_OUTSIDE_INSET
7339 */
7340 public void setScrollBarStyle(int style) {
7341 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
7342 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07007343 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 recomputePadding();
7345 }
7346 }
7347
7348 /**
7349 * <p>Returns the current scrollbar style.</p>
7350 * @return the current scrollbar style
7351 * @see #SCROLLBARS_INSIDE_OVERLAY
7352 * @see #SCROLLBARS_INSIDE_INSET
7353 * @see #SCROLLBARS_OUTSIDE_OVERLAY
7354 * @see #SCROLLBARS_OUTSIDE_INSET
7355 */
7356 public int getScrollBarStyle() {
7357 return mViewFlags & SCROLLBARS_STYLE_MASK;
7358 }
7359
7360 /**
7361 * <p>Compute the horizontal range that the horizontal scrollbar
7362 * represents.</p>
7363 *
7364 * <p>The range is expressed in arbitrary units that must be the same as the
7365 * units used by {@link #computeHorizontalScrollExtent()} and
7366 * {@link #computeHorizontalScrollOffset()}.</p>
7367 *
7368 * <p>The default range is the drawing width of this view.</p>
7369 *
7370 * @return the total horizontal range represented by the horizontal
7371 * scrollbar
7372 *
7373 * @see #computeHorizontalScrollExtent()
7374 * @see #computeHorizontalScrollOffset()
7375 * @see android.widget.ScrollBarDrawable
7376 */
7377 protected int computeHorizontalScrollRange() {
7378 return getWidth();
7379 }
7380
7381 /**
7382 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
7383 * within the horizontal range. This value is used to compute the position
7384 * of the thumb within the scrollbar's track.</p>
7385 *
7386 * <p>The range is expressed in arbitrary units that must be the same as the
7387 * units used by {@link #computeHorizontalScrollRange()} and
7388 * {@link #computeHorizontalScrollExtent()}.</p>
7389 *
7390 * <p>The default offset is the scroll offset of this view.</p>
7391 *
7392 * @return the horizontal offset of the scrollbar's thumb
7393 *
7394 * @see #computeHorizontalScrollRange()
7395 * @see #computeHorizontalScrollExtent()
7396 * @see android.widget.ScrollBarDrawable
7397 */
7398 protected int computeHorizontalScrollOffset() {
7399 return mScrollX;
7400 }
7401
7402 /**
7403 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
7404 * within the horizontal range. This value is used to compute the length
7405 * of the thumb within the scrollbar's track.</p>
7406 *
7407 * <p>The range is expressed in arbitrary units that must be the same as the
7408 * units used by {@link #computeHorizontalScrollRange()} and
7409 * {@link #computeHorizontalScrollOffset()}.</p>
7410 *
7411 * <p>The default extent is the drawing width of this view.</p>
7412 *
7413 * @return the horizontal extent of the scrollbar's thumb
7414 *
7415 * @see #computeHorizontalScrollRange()
7416 * @see #computeHorizontalScrollOffset()
7417 * @see android.widget.ScrollBarDrawable
7418 */
7419 protected int computeHorizontalScrollExtent() {
7420 return getWidth();
7421 }
7422
7423 /**
7424 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
7425 *
7426 * <p>The range is expressed in arbitrary units that must be the same as the
7427 * units used by {@link #computeVerticalScrollExtent()} and
7428 * {@link #computeVerticalScrollOffset()}.</p>
7429 *
7430 * @return the total vertical range represented by the vertical scrollbar
7431 *
7432 * <p>The default range is the drawing height of this view.</p>
7433 *
7434 * @see #computeVerticalScrollExtent()
7435 * @see #computeVerticalScrollOffset()
7436 * @see android.widget.ScrollBarDrawable
7437 */
7438 protected int computeVerticalScrollRange() {
7439 return getHeight();
7440 }
7441
7442 /**
7443 * <p>Compute the vertical offset of the vertical scrollbar's thumb
7444 * within the horizontal range. This value is used to compute the position
7445 * of the thumb within the scrollbar's track.</p>
7446 *
7447 * <p>The range is expressed in arbitrary units that must be the same as the
7448 * units used by {@link #computeVerticalScrollRange()} and
7449 * {@link #computeVerticalScrollExtent()}.</p>
7450 *
7451 * <p>The default offset is the scroll offset of this view.</p>
7452 *
7453 * @return the vertical offset of the scrollbar's thumb
7454 *
7455 * @see #computeVerticalScrollRange()
7456 * @see #computeVerticalScrollExtent()
7457 * @see android.widget.ScrollBarDrawable
7458 */
7459 protected int computeVerticalScrollOffset() {
7460 return mScrollY;
7461 }
7462
7463 /**
7464 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7465 * within the vertical range. This value is used to compute the length
7466 * of the thumb within the scrollbar's track.</p>
7467 *
7468 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08007469 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007470 * {@link #computeVerticalScrollOffset()}.</p>
7471 *
7472 * <p>The default extent is the drawing height of this view.</p>
7473 *
7474 * @return the vertical extent of the scrollbar's thumb
7475 *
7476 * @see #computeVerticalScrollRange()
7477 * @see #computeVerticalScrollOffset()
7478 * @see android.widget.ScrollBarDrawable
7479 */
7480 protected int computeVerticalScrollExtent() {
7481 return getHeight();
7482 }
7483
7484 /**
7485 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7486 * scrollbars are painted only if they have been awakened first.</p>
7487 *
7488 * @param canvas the canvas on which to draw the scrollbars
Joe Malin32736f02011-01-19 16:14:20 -08007489 *
Mike Cleronf116bf82009-09-27 19:14:12 -07007490 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007491 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08007492 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007493 // scrollbars are drawn only when the animation is running
7494 final ScrollabilityCache cache = mScrollCache;
7495 if (cache != null) {
Joe Malin32736f02011-01-19 16:14:20 -08007496
Mike Cleronf116bf82009-09-27 19:14:12 -07007497 int state = cache.state;
Joe Malin32736f02011-01-19 16:14:20 -08007498
Mike Cleronf116bf82009-09-27 19:14:12 -07007499 if (state == ScrollabilityCache.OFF) {
7500 return;
7501 }
Joe Malin32736f02011-01-19 16:14:20 -08007502
Mike Cleronf116bf82009-09-27 19:14:12 -07007503 boolean invalidate = false;
Joe Malin32736f02011-01-19 16:14:20 -08007504
Mike Cleronf116bf82009-09-27 19:14:12 -07007505 if (state == ScrollabilityCache.FADING) {
7506 // We're fading -- get our fade interpolation
7507 if (cache.interpolatorValues == null) {
7508 cache.interpolatorValues = new float[1];
7509 }
Joe Malin32736f02011-01-19 16:14:20 -08007510
Mike Cleronf116bf82009-09-27 19:14:12 -07007511 float[] values = cache.interpolatorValues;
Joe Malin32736f02011-01-19 16:14:20 -08007512
Mike Cleronf116bf82009-09-27 19:14:12 -07007513 // Stops the animation if we're done
7514 if (cache.scrollBarInterpolator.timeToValues(values) ==
7515 Interpolator.Result.FREEZE_END) {
7516 cache.state = ScrollabilityCache.OFF;
7517 } else {
7518 cache.scrollBar.setAlpha(Math.round(values[0]));
7519 }
Joe Malin32736f02011-01-19 16:14:20 -08007520
7521 // This will make the scroll bars inval themselves after
Mike Cleronf116bf82009-09-27 19:14:12 -07007522 // drawing. We only want this when we're fading so that
7523 // we prevent excessive redraws
7524 invalidate = true;
7525 } else {
7526 // We're just on -- but we may have been fading before so
7527 // reset alpha
7528 cache.scrollBar.setAlpha(255);
7529 }
7530
Joe Malin32736f02011-01-19 16:14:20 -08007531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007532 final int viewFlags = mViewFlags;
7533
7534 final boolean drawHorizontalScrollBar =
7535 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7536 final boolean drawVerticalScrollBar =
7537 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7538 && !isVerticalScrollBarHidden();
7539
7540 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7541 final int width = mRight - mLeft;
7542 final int height = mBottom - mTop;
7543
7544 final ScrollBarDrawable scrollBar = cache.scrollBar;
7545 int size = scrollBar.getSize(false);
7546 if (size <= 0) {
7547 size = cache.scrollBarSize;
7548 }
7549
Mike Reede8853fc2009-09-04 14:01:48 -04007550 final int scrollX = mScrollX;
7551 final int scrollY = mScrollY;
7552 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7553
Mike Cleronf116bf82009-09-27 19:14:12 -07007554 int left, top, right, bottom;
Joe Malin32736f02011-01-19 16:14:20 -08007555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007556 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07007557 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04007558 computeHorizontalScrollOffset(),
7559 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04007560 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07007561 getVerticalScrollbarWidth() : 0;
Joe Malin32736f02011-01-19 16:14:20 -08007562 top = scrollY + height - size - (mUserPaddingBottom & inside);
Mike Cleronf116bf82009-09-27 19:14:12 -07007563 left = scrollX + (mPaddingLeft & inside);
7564 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7565 bottom = top + size;
7566 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7567 if (invalidate) {
7568 invalidate(left, top, right, bottom);
7569 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007570 }
7571
7572 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04007573 scrollBar.setParameters(computeVerticalScrollRange(),
7574 computeVerticalScrollOffset(),
7575 computeVerticalScrollExtent(), true);
Adam Powell20232d02010-12-08 21:08:53 -08007576 switch (mVerticalScrollbarPosition) {
7577 default:
7578 case SCROLLBAR_POSITION_DEFAULT:
7579 case SCROLLBAR_POSITION_RIGHT:
7580 left = scrollX + width - size - (mUserPaddingRight & inside);
7581 break;
7582 case SCROLLBAR_POSITION_LEFT:
7583 left = scrollX + (mUserPaddingLeft & inside);
7584 break;
7585 }
Mike Cleronf116bf82009-09-27 19:14:12 -07007586 top = scrollY + (mPaddingTop & inside);
7587 right = left + size;
7588 bottom = scrollY + height - (mUserPaddingBottom & inside);
7589 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7590 if (invalidate) {
7591 invalidate(left, top, right, bottom);
7592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007593 }
7594 }
7595 }
7596 }
Romain Guy8506ab42009-06-11 17:35:47 -07007597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007598 /**
Romain Guy8506ab42009-06-11 17:35:47 -07007599 * 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 -08007600 * FastScroller is visible.
7601 * @return whether to temporarily hide the vertical scrollbar
7602 * @hide
7603 */
7604 protected boolean isVerticalScrollBarHidden() {
7605 return false;
7606 }
7607
7608 /**
7609 * <p>Draw the horizontal scrollbar if
7610 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7611 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007612 * @param canvas the canvas on which to draw the scrollbar
7613 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007614 *
7615 * @see #isHorizontalScrollBarEnabled()
7616 * @see #computeHorizontalScrollRange()
7617 * @see #computeHorizontalScrollExtent()
7618 * @see #computeHorizontalScrollOffset()
7619 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07007620 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007621 */
Romain Guy8fb95422010-08-17 18:38:51 -07007622 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7623 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007624 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007625 scrollBar.draw(canvas);
7626 }
Mike Reede8853fc2009-09-04 14:01:48 -04007627
Mike Reed4d6fe5f2009-09-03 13:29:05 -04007628 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007629 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7630 * returns true.</p>
7631 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 * @param canvas the canvas on which to draw the scrollbar
7633 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007634 *
7635 * @see #isVerticalScrollBarEnabled()
7636 * @see #computeVerticalScrollRange()
7637 * @see #computeVerticalScrollExtent()
7638 * @see #computeVerticalScrollOffset()
7639 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04007640 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641 */
Romain Guy8fb95422010-08-17 18:38:51 -07007642 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7643 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04007644 scrollBar.setBounds(l, t, r, b);
7645 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007646 }
7647
7648 /**
7649 * Implement this to do your drawing.
7650 *
7651 * @param canvas the canvas on which the background will be drawn
7652 */
7653 protected void onDraw(Canvas canvas) {
7654 }
7655
7656 /*
7657 * Caller is responsible for calling requestLayout if necessary.
7658 * (This allows addViewInLayout to not request a new layout.)
7659 */
7660 void assignParent(ViewParent parent) {
7661 if (mParent == null) {
7662 mParent = parent;
7663 } else if (parent == null) {
7664 mParent = null;
7665 } else {
7666 throw new RuntimeException("view " + this + " being added, but"
7667 + " it already has a parent");
7668 }
7669 }
7670
7671 /**
7672 * This is called when the view is attached to a window. At this point it
7673 * has a Surface and will start drawing. Note that this function is
7674 * guaranteed to be called before {@link #onDraw}, however it may be called
7675 * any time before the first onDraw -- including before or after
7676 * {@link #onMeasure}.
7677 *
7678 * @see #onDetachedFromWindow()
7679 */
7680 protected void onAttachedToWindow() {
7681 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7682 mParent.requestTransparentRegion(this);
7683 }
Adam Powell8568c3a2010-04-19 14:26:11 -07007684 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7685 initialAwakenScrollBars();
7686 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7687 }
Chet Haasea9b61ac2010-12-20 07:40:25 -08007688 jumpDrawablesToCurrentState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007689 }
7690
7691 /**
7692 * This is called when the view is detached from a window. At this point it
7693 * no longer has a surface for drawing.
7694 *
7695 * @see #onAttachedToWindow()
7696 */
7697 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08007698 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guy6c319ca2011-01-11 14:29:25 -08007699
Romain Guya440b002010-02-24 15:57:54 -08007700 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05007701 removeLongPressCallback();
Adam Powell3cb8b632011-01-21 15:34:14 -08007702 removePerformClickCallback();
Romain Guy6c319ca2011-01-11 14:29:25 -08007703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007704 destroyDrawingCache();
Romain Guy6c319ca2011-01-11 14:29:25 -08007705
7706 if (mHardwareLayer != null) {
7707 mHardwareLayer.destroy();
7708 mHardwareLayer = null;
7709 }
Romain Guy8dd5b1e2011-01-14 17:28:51 -08007710
Chet Haasedaf98e92011-01-10 14:10:36 -08007711 if (mDisplayList != null) {
7712 mDisplayList.invalidate();
7713 }
7714
Romain Guy8dd5b1e2011-01-14 17:28:51 -08007715 if (mAttachInfo != null) {
7716 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
7717 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this);
7718 }
7719
Patrick Dubroyec84c3a2011-01-13 17:55:37 -08007720 mCurrentAnimation = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007721 }
7722
7723 /**
7724 * @return The number of times this view has been attached to a window
7725 */
7726 protected int getWindowAttachCount() {
7727 return mWindowAttachCount;
7728 }
7729
7730 /**
7731 * Retrieve a unique token identifying the window this view is attached to.
7732 * @return Return the window's token for use in
7733 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7734 */
7735 public IBinder getWindowToken() {
7736 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7737 }
7738
7739 /**
7740 * Retrieve a unique token identifying the top-level "real" window of
7741 * the window that this view is attached to. That is, this is like
7742 * {@link #getWindowToken}, except if the window this view in is a panel
7743 * window (attached to another containing window), then the token of
7744 * the containing window is returned instead.
7745 *
7746 * @return Returns the associated window token, either
7747 * {@link #getWindowToken()} or the containing window's token.
7748 */
7749 public IBinder getApplicationWindowToken() {
7750 AttachInfo ai = mAttachInfo;
7751 if (ai != null) {
7752 IBinder appWindowToken = ai.mPanelParentWindowToken;
7753 if (appWindowToken == null) {
7754 appWindowToken = ai.mWindowToken;
7755 }
7756 return appWindowToken;
7757 }
7758 return null;
7759 }
7760
7761 /**
7762 * Retrieve private session object this view hierarchy is using to
7763 * communicate with the window manager.
7764 * @return the session object to communicate with the window manager
7765 */
7766 /*package*/ IWindowSession getWindowSession() {
7767 return mAttachInfo != null ? mAttachInfo.mSession : null;
7768 }
7769
7770 /**
7771 * @param info the {@link android.view.View.AttachInfo} to associated with
7772 * this view
7773 */
7774 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7775 //System.out.println("Attached! " + this);
7776 mAttachInfo = info;
7777 mWindowAttachCount++;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007778 // We will need to evaluate the drawable state at least once.
7779 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 if (mFloatingTreeObserver != null) {
7781 info.mTreeObserver.merge(mFloatingTreeObserver);
7782 mFloatingTreeObserver = null;
7783 }
7784 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7785 mAttachInfo.mScrollContainers.add(this);
7786 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7787 }
7788 performCollectViewAttributes(visibility);
7789 onAttachedToWindow();
7790 int vis = info.mWindowVisibility;
7791 if (vis != GONE) {
7792 onWindowVisibilityChanged(vis);
7793 }
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08007794 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7795 // If nobody has evaluated the drawable state yet, then do it now.
7796 refreshDrawableState();
7797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007798 }
7799
7800 void dispatchDetachedFromWindow() {
7801 //System.out.println("Detached! " + this);
7802 AttachInfo info = mAttachInfo;
7803 if (info != null) {
7804 int vis = info.mWindowVisibility;
7805 if (vis != GONE) {
7806 onWindowVisibilityChanged(GONE);
7807 }
7808 }
7809
7810 onDetachedFromWindow();
7811 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7812 mAttachInfo.mScrollContainers.remove(this);
7813 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7814 }
7815 mAttachInfo = null;
7816 }
7817
7818 /**
7819 * Store this view hierarchy's frozen state into the given container.
7820 *
7821 * @param container The SparseArray in which to save the view's state.
7822 *
7823 * @see #restoreHierarchyState
7824 * @see #dispatchSaveInstanceState
7825 * @see #onSaveInstanceState
7826 */
7827 public void saveHierarchyState(SparseArray<Parcelable> container) {
7828 dispatchSaveInstanceState(container);
7829 }
7830
7831 /**
7832 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7833 * May be overridden to modify how freezing happens to a view's children; for example, some
7834 * views may want to not store state for their children.
7835 *
7836 * @param container The SparseArray in which to save the view's state.
7837 *
7838 * @see #dispatchRestoreInstanceState
7839 * @see #saveHierarchyState
7840 * @see #onSaveInstanceState
7841 */
7842 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7843 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7844 mPrivateFlags &= ~SAVE_STATE_CALLED;
7845 Parcelable state = onSaveInstanceState();
7846 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7847 throw new IllegalStateException(
7848 "Derived class did not call super.onSaveInstanceState()");
7849 }
7850 if (state != null) {
7851 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7852 // + ": " + state);
7853 container.put(mID, state);
7854 }
7855 }
7856 }
7857
7858 /**
7859 * Hook allowing a view to generate a representation of its internal state
7860 * that can later be used to create a new instance with that same state.
7861 * This state should only contain information that is not persistent or can
7862 * not be reconstructed later. For example, you will never store your
7863 * current position on screen because that will be computed again when a
7864 * new instance of the view is placed in its view hierarchy.
7865 * <p>
7866 * Some examples of things you may store here: the current cursor position
7867 * in a text view (but usually not the text itself since that is stored in a
7868 * content provider or other persistent storage), the currently selected
7869 * item in a list view.
7870 *
7871 * @return Returns a Parcelable object containing the view's current dynamic
7872 * state, or null if there is nothing interesting to save. The
7873 * default implementation returns null.
7874 * @see #onRestoreInstanceState
7875 * @see #saveHierarchyState
7876 * @see #dispatchSaveInstanceState
7877 * @see #setSaveEnabled(boolean)
7878 */
7879 protected Parcelable onSaveInstanceState() {
7880 mPrivateFlags |= SAVE_STATE_CALLED;
7881 return BaseSavedState.EMPTY_STATE;
7882 }
7883
7884 /**
7885 * Restore this view hierarchy's frozen state from the given container.
7886 *
7887 * @param container The SparseArray which holds previously frozen states.
7888 *
7889 * @see #saveHierarchyState
7890 * @see #dispatchRestoreInstanceState
7891 * @see #onRestoreInstanceState
7892 */
7893 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7894 dispatchRestoreInstanceState(container);
7895 }
7896
7897 /**
7898 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7899 * children. May be overridden to modify how restoreing happens to a view's children; for
7900 * example, some views may want to not store state for their children.
7901 *
7902 * @param container The SparseArray which holds previously saved state.
7903 *
7904 * @see #dispatchSaveInstanceState
7905 * @see #restoreHierarchyState
7906 * @see #onRestoreInstanceState
7907 */
7908 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7909 if (mID != NO_ID) {
7910 Parcelable state = container.get(mID);
7911 if (state != null) {
7912 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7913 // + ": " + state);
7914 mPrivateFlags &= ~SAVE_STATE_CALLED;
7915 onRestoreInstanceState(state);
7916 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7917 throw new IllegalStateException(
7918 "Derived class did not call super.onRestoreInstanceState()");
7919 }
7920 }
7921 }
7922 }
7923
7924 /**
7925 * Hook allowing a view to re-apply a representation of its internal state that had previously
7926 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7927 * null state.
7928 *
7929 * @param state The frozen state that had previously been returned by
7930 * {@link #onSaveInstanceState}.
7931 *
7932 * @see #onSaveInstanceState
7933 * @see #restoreHierarchyState
7934 * @see #dispatchRestoreInstanceState
7935 */
7936 protected void onRestoreInstanceState(Parcelable state) {
7937 mPrivateFlags |= SAVE_STATE_CALLED;
7938 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007939 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7940 + "received " + state.getClass().toString() + " instead. This usually happens "
Joe Malin32736f02011-01-19 16:14:20 -08007941 + "when two views of different type have the same id in the same hierarchy. "
7942 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
Romain Guy237c1ce2009-12-08 11:30:25 -08007943 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007944 }
7945 }
7946
7947 /**
7948 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7949 *
7950 * @return the drawing start time in milliseconds
7951 */
7952 public long getDrawingTime() {
7953 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7954 }
7955
7956 /**
7957 * <p>Enables or disables the duplication of the parent's state into this view. When
7958 * duplication is enabled, this view gets its drawable state from its parent rather
7959 * than from its own internal properties.</p>
7960 *
7961 * <p>Note: in the current implementation, setting this property to true after the
7962 * view was added to a ViewGroup might have no effect at all. This property should
7963 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7964 *
7965 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7966 * property is enabled, an exception will be thrown.</p>
Joe Malin32736f02011-01-19 16:14:20 -08007967 *
Gilles Debunnefb817032011-01-13 13:52:49 -08007968 * <p>Note: if the child view uses and updates additionnal states which are unknown to the
7969 * parent, these states should not be affected by this method.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007970 *
7971 * @param enabled True to enable duplication of the parent's drawable state, false
7972 * to disable it.
7973 *
7974 * @see #getDrawableState()
7975 * @see #isDuplicateParentStateEnabled()
7976 */
7977 public void setDuplicateParentStateEnabled(boolean enabled) {
7978 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7979 }
7980
7981 /**
7982 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7983 *
7984 * @return True if this view's drawable state is duplicated from the parent,
7985 * false otherwise
7986 *
7987 * @see #getDrawableState()
7988 * @see #setDuplicateParentStateEnabled(boolean)
7989 */
7990 public boolean isDuplicateParentStateEnabled() {
7991 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7992 }
7993
7994 /**
Romain Guy171c5922011-01-06 10:04:23 -08007995 * <p>Specifies the type of layer backing this view. The layer can be
7996 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
7997 * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
Joe Malin32736f02011-01-19 16:14:20 -08007998 *
Romain Guy171c5922011-01-06 10:04:23 -08007999 * <p>A layer is associated with an optional {@link android.graphics.Paint}
8000 * instance that controls how the layer is composed on screen. The following
8001 * properties of the paint are taken into account when composing the layer:</p>
8002 * <ul>
8003 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
8004 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
8005 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
8006 * </ul>
Joe Malin32736f02011-01-19 16:14:20 -08008007 *
Romain Guy171c5922011-01-06 10:04:23 -08008008 * <p>If this view has an alpha value set to < 1.0 by calling
8009 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
8010 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
8011 * equivalent to setting a hardware layer on this view and providing a paint with
8012 * the desired alpha value.<p>
Joe Malin32736f02011-01-19 16:14:20 -08008013 *
Romain Guy171c5922011-01-06 10:04:23 -08008014 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
8015 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
8016 * for more information on when and how to use layers.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008017 *
Romain Guy171c5922011-01-06 10:04:23 -08008018 * @param layerType The ype of layer to use with this view, must be one of
8019 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
8020 * {@link #LAYER_TYPE_HARDWARE}
8021 * @param paint The paint used to compose the layer. This argument is optional
8022 * and can be null. It is ignored when the layer type is
8023 * {@link #LAYER_TYPE_NONE}
Joe Malin32736f02011-01-19 16:14:20 -08008024 *
8025 * @see #getLayerType()
Romain Guy171c5922011-01-06 10:04:23 -08008026 * @see #LAYER_TYPE_NONE
8027 * @see #LAYER_TYPE_SOFTWARE
8028 * @see #LAYER_TYPE_HARDWARE
Joe Malin32736f02011-01-19 16:14:20 -08008029 * @see #setAlpha(float)
8030 *
Romain Guy171c5922011-01-06 10:04:23 -08008031 * @attr ref android.R.styleable#View_layerType
8032 */
8033 public void setLayerType(int layerType, Paint paint) {
8034 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
Joe Malin32736f02011-01-19 16:14:20 -08008035 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
Romain Guy171c5922011-01-06 10:04:23 -08008036 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
8037 }
Chet Haasedaf98e92011-01-10 14:10:36 -08008038
Romain Guyd6cd5722011-01-17 14:42:41 -08008039 if (layerType == mLayerType) {
8040 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
8041 mLayerPaint = paint == null ? new Paint() : paint;
Romain Guy0fd89bf2011-01-26 15:41:30 -08008042 invalidateParentCaches();
8043 invalidate(true);
Romain Guyd6cd5722011-01-17 14:42:41 -08008044 }
8045 return;
8046 }
Romain Guy171c5922011-01-06 10:04:23 -08008047
8048 // Destroy any previous software drawing cache if needed
Romain Guy6c319ca2011-01-11 14:29:25 -08008049 switch (mLayerType) {
8050 case LAYER_TYPE_SOFTWARE:
8051 if (mDrawingCache != null) {
8052 mDrawingCache.recycle();
8053 mDrawingCache = null;
8054 }
Joe Malin32736f02011-01-19 16:14:20 -08008055
Romain Guy6c319ca2011-01-11 14:29:25 -08008056 if (mUnscaledDrawingCache != null) {
8057 mUnscaledDrawingCache.recycle();
8058 mUnscaledDrawingCache = null;
8059 }
8060 break;
8061 case LAYER_TYPE_HARDWARE:
8062 if (mHardwareLayer != null) {
8063 mHardwareLayer.destroy();
8064 mHardwareLayer = null;
8065 }
8066 break;
8067 default:
8068 break;
Romain Guy171c5922011-01-06 10:04:23 -08008069 }
8070
8071 mLayerType = layerType;
Romain Guyd6cd5722011-01-17 14:42:41 -08008072 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : (paint == null ? new Paint() : paint);
Romain Guy171c5922011-01-06 10:04:23 -08008073
Romain Guy0fd89bf2011-01-26 15:41:30 -08008074 invalidateParentCaches();
8075 invalidate(true);
Romain Guy171c5922011-01-06 10:04:23 -08008076 }
8077
8078 /**
8079 * Indicates what type of layer is currently associated with this view. By default
8080 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
8081 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
8082 * for more information on the different types of layers.
Joe Malin32736f02011-01-19 16:14:20 -08008083 *
Romain Guy171c5922011-01-06 10:04:23 -08008084 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
8085 * {@link #LAYER_TYPE_HARDWARE}
Joe Malin32736f02011-01-19 16:14:20 -08008086 *
8087 * @see #setLayerType(int, android.graphics.Paint)
Romain Guy171c5922011-01-06 10:04:23 -08008088 * @see #LAYER_TYPE_NONE
8089 * @see #LAYER_TYPE_SOFTWARE
8090 * @see #LAYER_TYPE_HARDWARE
8091 */
8092 public int getLayerType() {
8093 return mLayerType;
8094 }
Joe Malin32736f02011-01-19 16:14:20 -08008095
Romain Guy6c319ca2011-01-11 14:29:25 -08008096 /**
8097 * <p>Returns a hardware layer that can be used to draw this view again
8098 * without executing its draw method.</p>
8099 *
8100 * @return A HardwareLayer ready to render, or null if an error occurred.
8101 */
Romain Guy5e7f7662011-01-24 22:35:56 -08008102 HardwareLayer getHardwareLayer() {
Romain Guy6c319ca2011-01-11 14:29:25 -08008103 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8104 return null;
8105 }
8106
8107 final int width = mRight - mLeft;
8108 final int height = mBottom - mTop;
Joe Malin32736f02011-01-19 16:14:20 -08008109
Romain Guy6c319ca2011-01-11 14:29:25 -08008110 if (width == 0 || height == 0) {
8111 return null;
8112 }
8113
8114 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
8115 if (mHardwareLayer == null) {
8116 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
8117 width, height, isOpaque());
8118 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
8119 mHardwareLayer.resize(width, height);
8120 }
8121
Romain Guy5e7f7662011-01-24 22:35:56 -08008122 Canvas currentCanvas = mAttachInfo.mHardwareCanvas;
8123 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
8124 mAttachInfo.mHardwareCanvas = canvas;
Romain Guy6c319ca2011-01-11 14:29:25 -08008125 try {
8126 canvas.setViewport(width, height);
Romain Guy7d7b5492011-01-24 16:33:45 -08008127 // TODO: We should pass the dirty rect
8128 canvas.onPreDraw(null);
Romain Guy6c319ca2011-01-11 14:29:25 -08008129
Romain Guy4f09f542011-01-26 22:41:43 -08008130 final int restoreCount = canvas.save();
8131
Romain Guy6c319ca2011-01-11 14:29:25 -08008132 computeScroll();
8133 canvas.translate(-mScrollX, -mScrollY);
8134
Romain Guy6c319ca2011-01-11 14:29:25 -08008135 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Joe Malin32736f02011-01-19 16:14:20 -08008136
Romain Guy6c319ca2011-01-11 14:29:25 -08008137 // Fast path for layouts with no backgrounds
8138 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8139 mPrivateFlags &= ~DIRTY_MASK;
8140 dispatchDraw(canvas);
8141 } else {
8142 draw(canvas);
8143 }
Joe Malin32736f02011-01-19 16:14:20 -08008144
Romain Guy6c319ca2011-01-11 14:29:25 -08008145 canvas.restoreToCount(restoreCount);
8146 } finally {
8147 canvas.onPostDraw();
Romain Guy5e7f7662011-01-24 22:35:56 -08008148 mHardwareLayer.end(currentCanvas);
8149 mAttachInfo.mHardwareCanvas = currentCanvas;
Romain Guy6c319ca2011-01-11 14:29:25 -08008150 }
8151 }
8152
8153 return mHardwareLayer;
8154 }
Romain Guy171c5922011-01-06 10:04:23 -08008155
8156 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
8158 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
8159 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
8160 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
8161 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
8162 * null.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008163 *
Romain Guy171c5922011-01-06 10:04:23 -08008164 * <p>Enabling the drawing cache is similar to
8165 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
Chet Haasedaf98e92011-01-10 14:10:36 -08008166 * acceleration is turned off. When hardware acceleration is turned on, enabling the
8167 * drawing cache has no effect on rendering because the system uses a different mechanism
8168 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
8169 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
8170 * for information on how to enable software and hardware layers.</p>
8171 *
8172 * <p>This API can be used to manually generate
8173 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
8174 * {@link #getDrawingCache()}.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 *
8176 * @param enabled true to enable the drawing cache, false otherwise
8177 *
8178 * @see #isDrawingCacheEnabled()
8179 * @see #getDrawingCache()
8180 * @see #buildDrawingCache()
Joe Malin32736f02011-01-19 16:14:20 -08008181 * @see #setLayerType(int, android.graphics.Paint)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008182 */
8183 public void setDrawingCacheEnabled(boolean enabled) {
8184 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
8185 }
8186
8187 /**
8188 * <p>Indicates whether the drawing cache is enabled for this view.</p>
8189 *
8190 * @return true if the drawing cache is enabled
8191 *
8192 * @see #setDrawingCacheEnabled(boolean)
8193 * @see #getDrawingCache()
8194 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07008195 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008196 public boolean isDrawingCacheEnabled() {
8197 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
8198 }
8199
8200 /**
Chet Haasedaf98e92011-01-10 14:10:36 -08008201 * Debugging utility which recursively outputs the dirty state of a view and its
8202 * descendants.
Joe Malin32736f02011-01-19 16:14:20 -08008203 *
Chet Haasedaf98e92011-01-10 14:10:36 -08008204 * @hide
8205 */
8206 public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
8207 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
8208 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
8209 (mPrivateFlags & View.DRAWING_CACHE_VALID) +
8210 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
8211 if (clear) {
8212 mPrivateFlags &= clearMask;
8213 }
8214 if (this instanceof ViewGroup) {
8215 ViewGroup parent = (ViewGroup) this;
8216 final int count = parent.getChildCount();
8217 for (int i = 0; i < count; i++) {
Romain Guy7d7b5492011-01-24 16:33:45 -08008218 final View child = parent.getChildAt(i);
Chet Haasedaf98e92011-01-10 14:10:36 -08008219 child.outputDirtyFlags(indent + " ", clear, clearMask);
8220 }
8221 }
8222 }
8223
8224 /**
8225 * This method is used by ViewGroup to cause its children to restore or recreate their
8226 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
8227 * to recreate its own display list, which would happen if it went through the normal
8228 * draw/dispatchDraw mechanisms.
8229 *
8230 * @hide
8231 */
8232 protected void dispatchGetDisplayList() {}
Chet Haasef4ac5472011-01-27 10:30:25 -08008233
8234 /**
8235 * A view that is not attached or hardware accelerated cannot create a display list.
8236 * This method checks these conditions and returns the appropriate result.
8237 *
8238 * @return true if view has the ability to create a display list, false otherwise.
8239 *
8240 * @hide
8241 */
8242 public boolean canHaveDisplayList() {
8243 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8244 return false;
8245 }
8246 return true;
8247 }
Joe Malin32736f02011-01-19 16:14:20 -08008248
Chet Haasedaf98e92011-01-10 14:10:36 -08008249 /**
Romain Guyb051e892010-09-28 19:09:36 -07008250 * <p>Returns a display list that can be used to draw this view again
8251 * without executing its draw method.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008252 *
Romain Guyb051e892010-09-28 19:09:36 -07008253 * @return A DisplayList ready to replay, or null if caching is not enabled.
Chet Haasedaf98e92011-01-10 14:10:36 -08008254 *
8255 * @hide
Romain Guyb051e892010-09-28 19:09:36 -07008256 */
Chet Haasedaf98e92011-01-10 14:10:36 -08008257 public DisplayList getDisplayList() {
Chet Haasef4ac5472011-01-27 10:30:25 -08008258 if (!canHaveDisplayList()) {
Romain Guyb051e892010-09-28 19:09:36 -07008259 return null;
8260 }
8261
Chet Haasedaf98e92011-01-10 14:10:36 -08008262 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
8263 mDisplayList == null || !mDisplayList.isValid() ||
8264 mRecreateDisplayList)) {
8265 // Don't need to recreate the display list, just need to tell our
8266 // children to restore/recreate theirs
8267 if (mDisplayList != null && mDisplayList.isValid() &&
8268 !mRecreateDisplayList) {
8269 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8270 mPrivateFlags &= ~DIRTY_MASK;
8271 dispatchGetDisplayList();
8272
8273 return mDisplayList;
8274 }
8275
8276 // If we got here, we're recreating it. Mark it as such to ensure that
8277 // we copy in child display lists into ours in drawChild()
8278 mRecreateDisplayList = true;
Chet Haase9e90a992011-01-04 16:23:21 -08008279 if (mDisplayList == null) {
Chet Haasedaf98e92011-01-10 14:10:36 -08008280 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(this);
8281 // If we're creating a new display list, make sure our parent gets invalidated
8282 // since they will need to recreate their display list to account for this
8283 // new child display list.
Romain Guy0fd89bf2011-01-26 15:41:30 -08008284 invalidateParentCaches();
Chet Haase9e90a992011-01-04 16:23:21 -08008285 }
Romain Guyb051e892010-09-28 19:09:36 -07008286
8287 final HardwareCanvas canvas = mDisplayList.start();
8288 try {
8289 int width = mRight - mLeft;
8290 int height = mBottom - mTop;
8291
8292 canvas.setViewport(width, height);
Romain Guy7d7b5492011-01-24 16:33:45 -08008293 // The dirty rect should always be null for a display list
8294 canvas.onPreDraw(null);
Romain Guyb051e892010-09-28 19:09:36 -07008295
8296 final int restoreCount = canvas.save();
8297
Chet Haasedaf98e92011-01-10 14:10:36 -08008298 computeScroll();
8299 canvas.translate(-mScrollX, -mScrollY);
Romain Guy2fe9a8f2010-10-04 20:17:01 -07008300 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
Joe Malin32736f02011-01-19 16:14:20 -08008301
Romain Guyb051e892010-09-28 19:09:36 -07008302 // Fast path for layouts with no backgrounds
8303 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8304 mPrivateFlags &= ~DIRTY_MASK;
8305 dispatchDraw(canvas);
8306 } else {
8307 draw(canvas);
8308 }
Joe Malin32736f02011-01-19 16:14:20 -08008309
Romain Guyb051e892010-09-28 19:09:36 -07008310 canvas.restoreToCount(restoreCount);
8311 } finally {
8312 canvas.onPostDraw();
8313
8314 mDisplayList.end();
Romain Guyb051e892010-09-28 19:09:36 -07008315 }
Chet Haase77785f92011-01-25 23:22:09 -08008316 } else {
8317 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8318 mPrivateFlags &= ~DIRTY_MASK;
Romain Guyb051e892010-09-28 19:09:36 -07008319 }
8320
8321 return mDisplayList;
8322 }
8323
8324 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008325 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008326 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008327 * @return A non-scaled bitmap representing this view or null if cache is disabled.
Joe Malin32736f02011-01-19 16:14:20 -08008328 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008329 * @see #getDrawingCache(boolean)
8330 */
8331 public Bitmap getDrawingCache() {
8332 return getDrawingCache(false);
8333 }
8334
8335 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008336 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
8337 * is null when caching is disabled. If caching is enabled and the cache is not ready,
8338 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
8339 * draw from the cache when the cache is enabled. To benefit from the cache, you must
8340 * request the drawing cache by calling this method and draw it on screen if the
8341 * returned bitmap is not null.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008342 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008343 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8344 * this method will create a bitmap of the same size as this view. Because this bitmap
8345 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8346 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8347 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8348 * size than the view. This implies that your application must be able to handle this
8349 * size.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008350 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008351 * @param autoScale Indicates whether the generated bitmap should be scaled based on
8352 * the current density of the screen when the application is in compatibility
8353 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008354 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008355 * @return A bitmap representing this view or null if cache is disabled.
Joe Malin32736f02011-01-19 16:14:20 -08008356 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008357 * @see #setDrawingCacheEnabled(boolean)
8358 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07008359 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008360 * @see #destroyDrawingCache()
8361 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008362 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008363 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8364 return null;
8365 }
8366 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008367 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008368 }
Romain Guy02890fd2010-08-06 17:58:44 -07008369 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008370 }
8371
8372 /**
8373 * <p>Frees the resources used by the drawing cache. If you call
8374 * {@link #buildDrawingCache()} manually without calling
8375 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8376 * should cleanup the cache with this method afterwards.</p>
8377 *
8378 * @see #setDrawingCacheEnabled(boolean)
8379 * @see #buildDrawingCache()
8380 * @see #getDrawingCache()
8381 */
8382 public void destroyDrawingCache() {
8383 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008384 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008385 mDrawingCache = null;
8386 }
Romain Guyfbd8f692009-06-26 14:51:58 -07008387 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07008388 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07008389 mUnscaledDrawingCache = null;
8390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008391 }
8392
8393 /**
8394 * Setting a solid background color for the drawing cache's bitmaps will improve
8395 * perfromance and memory usage. Note, though that this should only be used if this
8396 * view will always be drawn on top of a solid color.
8397 *
8398 * @param color The background color to use for the drawing cache's bitmap
8399 *
8400 * @see #setDrawingCacheEnabled(boolean)
8401 * @see #buildDrawingCache()
8402 * @see #getDrawingCache()
8403 */
8404 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08008405 if (color != mDrawingCacheBackgroundColor) {
8406 mDrawingCacheBackgroundColor = color;
8407 mPrivateFlags &= ~DRAWING_CACHE_VALID;
8408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 }
8410
8411 /**
8412 * @see #setDrawingCacheBackgroundColor(int)
8413 *
8414 * @return The background color to used for the drawing cache's bitmap
8415 */
8416 public int getDrawingCacheBackgroundColor() {
8417 return mDrawingCacheBackgroundColor;
8418 }
8419
8420 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07008421 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008422 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008423 * @see #buildDrawingCache(boolean)
8424 */
8425 public void buildDrawingCache() {
8426 buildDrawingCache(false);
8427 }
8428
8429 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008430 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
8431 *
8432 * <p>If you call {@link #buildDrawingCache()} manually without calling
8433 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8434 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008435 *
Romain Guyfbd8f692009-06-26 14:51:58 -07008436 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8437 * this method will create a bitmap of the same size as this view. Because this bitmap
8438 * will be drawn scaled by the parent ViewGroup, the result on screen might show
8439 * scaling artifacts. To avoid such artifacts, you should call this method by setting
8440 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8441 * size than the view. This implies that your application must be able to handle this
8442 * size.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008443 *
Romain Guy0d9275e2010-10-26 14:22:30 -07008444 * <p>You should avoid calling this method when hardware acceleration is enabled. If
8445 * you do not need the drawing cache bitmap, calling this method will increase memory
Joe Malin32736f02011-01-19 16:14:20 -08008446 * usage and cause the view to be rendered in software once, thus negatively impacting
Romain Guy0d9275e2010-10-26 14:22:30 -07008447 * performance.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008448 *
8449 * @see #getDrawingCache()
8450 * @see #destroyDrawingCache()
8451 */
Romain Guyfbd8f692009-06-26 14:51:58 -07008452 public void buildDrawingCache(boolean autoScale) {
8453 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07008454 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008455
8456 if (ViewDebug.TRACE_HIERARCHY) {
8457 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
8458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008459
Romain Guy8506ab42009-06-11 17:35:47 -07008460 int width = mRight - mLeft;
8461 int height = mBottom - mTop;
8462
8463 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07008464 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07008465
Romain Guye1123222009-06-29 14:24:56 -07008466 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008467 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
8468 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07008469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008470
8471 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07008472 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Adam Powell26153a32010-11-08 15:22:27 -08008473 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008474
8475 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07008476 // Projected bitmap size in bytes
Adam Powell26153a32010-11-08 15:22:27 -08008477 (width * height * (opaque && !use32BitCache ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008478 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
8479 destroyDrawingCache();
8480 return;
8481 }
8482
8483 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07008484 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008485
8486 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008487 Bitmap.Config quality;
8488 if (!opaque) {
8489 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
8490 case DRAWING_CACHE_QUALITY_AUTO:
8491 quality = Bitmap.Config.ARGB_8888;
8492 break;
8493 case DRAWING_CACHE_QUALITY_LOW:
8494 quality = Bitmap.Config.ARGB_4444;
8495 break;
8496 case DRAWING_CACHE_QUALITY_HIGH:
8497 quality = Bitmap.Config.ARGB_8888;
8498 break;
8499 default:
8500 quality = Bitmap.Config.ARGB_8888;
8501 break;
8502 }
8503 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07008504 // Optimization for translucent windows
8505 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
Adam Powell26153a32010-11-08 15:22:27 -08008506 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008507 }
8508
8509 // Try to cleanup memory
8510 if (bitmap != null) bitmap.recycle();
8511
8512 try {
8513 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07008514 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07008515 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07008516 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008517 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07008518 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07008519 }
Adam Powell26153a32010-11-08 15:22:27 -08008520 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008521 } catch (OutOfMemoryError e) {
8522 // If there is not enough memory to create the bitmap cache, just
8523 // ignore the issue as bitmap caches are not required to draw the
8524 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07008525 if (autoScale) {
8526 mDrawingCache = null;
8527 } else {
8528 mUnscaledDrawingCache = null;
8529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 return;
8531 }
8532
8533 clear = drawingCacheBackgroundColor != 0;
8534 }
8535
8536 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008537 if (attachInfo != null) {
8538 canvas = attachInfo.mCanvas;
8539 if (canvas == null) {
8540 canvas = new Canvas();
8541 }
8542 canvas.setBitmap(bitmap);
8543 // Temporarily clobber the cached Canvas in case one of our children
8544 // is also using a drawing cache. Without this, the children would
8545 // steal the canvas by attaching their own bitmap to it and bad, bad
8546 // thing would happen (invisible views, corrupted drawings, etc.)
8547 attachInfo.mCanvas = null;
8548 } else {
8549 // This case should hopefully never or seldom happen
8550 canvas = new Canvas(bitmap);
8551 }
8552
8553 if (clear) {
8554 bitmap.eraseColor(drawingCacheBackgroundColor);
8555 }
8556
8557 computeScroll();
8558 final int restoreCount = canvas.save();
Joe Malin32736f02011-01-19 16:14:20 -08008559
Romain Guye1123222009-06-29 14:24:56 -07008560 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07008561 final float scale = attachInfo.mApplicationScale;
8562 canvas.scale(scale, scale);
8563 }
Joe Malin32736f02011-01-19 16:14:20 -08008564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008565 canvas.translate(-mScrollX, -mScrollY);
8566
Romain Guy5bcdff42009-05-14 21:27:18 -07008567 mPrivateFlags |= DRAWN;
Romain Guy171c5922011-01-06 10:04:23 -08008568 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
8569 mLayerType != LAYER_TYPE_NONE) {
Romain Guy0d9275e2010-10-26 14:22:30 -07008570 mPrivateFlags |= DRAWING_CACHE_VALID;
8571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008572
8573 // Fast path for layouts with no backgrounds
8574 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8575 if (ViewDebug.TRACE_HIERARCHY) {
8576 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8577 }
Romain Guy5bcdff42009-05-14 21:27:18 -07008578 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 dispatchDraw(canvas);
8580 } else {
8581 draw(canvas);
8582 }
8583
8584 canvas.restoreToCount(restoreCount);
8585
8586 if (attachInfo != null) {
8587 // Restore the cached Canvas for our siblings
8588 attachInfo.mCanvas = canvas;
8589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590 }
8591 }
8592
8593 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008594 * Create a snapshot of the view into a bitmap. We should probably make
8595 * some form of this public, but should think about the API.
8596 */
Romain Guy223ff5c2010-03-02 17:07:47 -08008597 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008598 int width = mRight - mLeft;
8599 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008600
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008601 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07008602 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008603 width = (int) ((width * scale) + 0.5f);
8604 height = (int) ((height * scale) + 0.5f);
Joe Malin32736f02011-01-19 16:14:20 -08008605
Romain Guy8c11e312009-09-14 15:15:30 -07008606 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008607 if (bitmap == null) {
8608 throw new OutOfMemoryError();
8609 }
8610
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008611 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Joe Malin32736f02011-01-19 16:14:20 -08008612
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008613 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008614 if (attachInfo != null) {
8615 canvas = attachInfo.mCanvas;
8616 if (canvas == null) {
8617 canvas = new Canvas();
8618 }
8619 canvas.setBitmap(bitmap);
8620 // Temporarily clobber the cached Canvas in case one of our children
8621 // is also using a drawing cache. Without this, the children would
8622 // steal the canvas by attaching their own bitmap to it and bad, bad
8623 // things would happen (invisible views, corrupted drawings, etc.)
8624 attachInfo.mCanvas = null;
8625 } else {
8626 // This case should hopefully never or seldom happen
8627 canvas = new Canvas(bitmap);
8628 }
8629
Romain Guy5bcdff42009-05-14 21:27:18 -07008630 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008631 bitmap.eraseColor(backgroundColor);
8632 }
8633
8634 computeScroll();
8635 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07008636 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008637 canvas.translate(-mScrollX, -mScrollY);
8638
Romain Guy5bcdff42009-05-14 21:27:18 -07008639 // Temporarily remove the dirty mask
8640 int flags = mPrivateFlags;
8641 mPrivateFlags &= ~DIRTY_MASK;
8642
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008643 // Fast path for layouts with no backgrounds
8644 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8645 dispatchDraw(canvas);
8646 } else {
8647 draw(canvas);
8648 }
8649
Romain Guy5bcdff42009-05-14 21:27:18 -07008650 mPrivateFlags = flags;
8651
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008652 canvas.restoreToCount(restoreCount);
8653
8654 if (attachInfo != null) {
8655 // Restore the cached Canvas for our siblings
8656 attachInfo.mCanvas = canvas;
8657 }
Romain Guy8506ab42009-06-11 17:35:47 -07008658
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07008659 return bitmap;
8660 }
8661
8662 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 * Indicates whether this View is currently in edit mode. A View is usually
8664 * in edit mode when displayed within a developer tool. For instance, if
8665 * this View is being drawn by a visual user interface builder, this method
8666 * should return true.
8667 *
8668 * Subclasses should check the return value of this method to provide
8669 * different behaviors if their normal behavior might interfere with the
8670 * host environment. For instance: the class spawns a thread in its
8671 * constructor, the drawing code relies on device-specific features, etc.
8672 *
8673 * This method is usually checked in the drawing code of custom widgets.
8674 *
8675 * @return True if this View is in edit mode, false otherwise.
8676 */
8677 public boolean isInEditMode() {
8678 return false;
8679 }
8680
8681 /**
8682 * If the View draws content inside its padding and enables fading edges,
8683 * it needs to support padding offsets. Padding offsets are added to the
8684 * fading edges to extend the length of the fade so that it covers pixels
8685 * drawn inside the padding.
8686 *
8687 * Subclasses of this class should override this method if they need
8688 * to draw content inside the padding.
8689 *
8690 * @return True if padding offset must be applied, false otherwise.
8691 *
8692 * @see #getLeftPaddingOffset()
8693 * @see #getRightPaddingOffset()
8694 * @see #getTopPaddingOffset()
8695 * @see #getBottomPaddingOffset()
8696 *
8697 * @since CURRENT
8698 */
8699 protected boolean isPaddingOffsetRequired() {
8700 return false;
8701 }
8702
8703 /**
8704 * Amount by which to extend the left fading region. Called only when
8705 * {@link #isPaddingOffsetRequired()} returns true.
8706 *
8707 * @return The left padding offset in pixels.
8708 *
8709 * @see #isPaddingOffsetRequired()
8710 *
8711 * @since CURRENT
8712 */
8713 protected int getLeftPaddingOffset() {
8714 return 0;
8715 }
8716
8717 /**
8718 * Amount by which to extend the right fading region. Called only when
8719 * {@link #isPaddingOffsetRequired()} returns true.
8720 *
8721 * @return The right padding offset in pixels.
8722 *
8723 * @see #isPaddingOffsetRequired()
8724 *
8725 * @since CURRENT
8726 */
8727 protected int getRightPaddingOffset() {
8728 return 0;
8729 }
8730
8731 /**
8732 * Amount by which to extend the top fading region. Called only when
8733 * {@link #isPaddingOffsetRequired()} returns true.
8734 *
8735 * @return The top padding offset in pixels.
8736 *
8737 * @see #isPaddingOffsetRequired()
8738 *
8739 * @since CURRENT
8740 */
8741 protected int getTopPaddingOffset() {
8742 return 0;
8743 }
8744
8745 /**
8746 * Amount by which to extend the bottom fading region. Called only when
8747 * {@link #isPaddingOffsetRequired()} returns true.
8748 *
8749 * @return The bottom padding offset in pixels.
8750 *
8751 * @see #isPaddingOffsetRequired()
8752 *
8753 * @since CURRENT
8754 */
8755 protected int getBottomPaddingOffset() {
8756 return 0;
8757 }
8758
8759 /**
Romain Guy2bffd262010-09-12 17:40:02 -07008760 * <p>Indicates whether this view is attached to an hardware accelerated
8761 * window or not.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008762 *
Romain Guy2bffd262010-09-12 17:40:02 -07008763 * <p>Even if this method returns true, it does not mean that every call
8764 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8765 * accelerated {@link android.graphics.Canvas}. For instance, if this view
8766 * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8767 * window is hardware accelerated,
8768 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8769 * return false, and this method will return true.</p>
Joe Malin32736f02011-01-19 16:14:20 -08008770 *
Romain Guy2bffd262010-09-12 17:40:02 -07008771 * @return True if the view is attached to a window and the window is
8772 * hardware accelerated; false in any other case.
8773 */
8774 public boolean isHardwareAccelerated() {
8775 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8776 }
Joe Malin32736f02011-01-19 16:14:20 -08008777
Romain Guy2bffd262010-09-12 17:40:02 -07008778 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008779 * Manually render this view (and all of its children) to the given Canvas.
8780 * The view must have already done a full layout before this function is
Chet Haasec75ec332010-12-17 07:44:30 -08008781 * called. When implementing a view, implement {@link #onDraw} instead of
8782 * overriding this method. If you do need to override this method, call
8783 * the superclass version.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008784 *
8785 * @param canvas The Canvas to which the View is rendered.
8786 */
8787 public void draw(Canvas canvas) {
8788 if (ViewDebug.TRACE_HIERARCHY) {
8789 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8790 }
8791
Romain Guy5bcdff42009-05-14 21:27:18 -07008792 final int privateFlags = mPrivateFlags;
8793 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8794 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8795 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07008796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008797 /*
8798 * Draw traversal performs several drawing steps which must be executed
8799 * in the appropriate order:
8800 *
8801 * 1. Draw the background
8802 * 2. If necessary, save the canvas' layers to prepare for fading
8803 * 3. Draw view's content
8804 * 4. Draw children
8805 * 5. If necessary, draw the fading edges and restore layers
8806 * 6. Draw decorations (scrollbars for instance)
8807 */
8808
8809 // Step 1, draw the background, if needed
8810 int saveCount;
8811
Romain Guy24443ea2009-05-11 11:56:30 -07008812 if (!dirtyOpaque) {
8813 final Drawable background = mBGDrawable;
8814 if (background != null) {
8815 final int scrollX = mScrollX;
8816 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008817
Romain Guy24443ea2009-05-11 11:56:30 -07008818 if (mBackgroundSizeChanged) {
8819 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8820 mBackgroundSizeChanged = false;
8821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008822
Romain Guy24443ea2009-05-11 11:56:30 -07008823 if ((scrollX | scrollY) == 0) {
8824 background.draw(canvas);
8825 } else {
8826 canvas.translate(scrollX, scrollY);
8827 background.draw(canvas);
8828 canvas.translate(-scrollX, -scrollY);
8829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008830 }
8831 }
8832
8833 // skip step 2 & 5 if possible (common case)
8834 final int viewFlags = mViewFlags;
8835 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8836 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8837 if (!verticalEdges && !horizontalEdges) {
8838 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008839 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008840
8841 // Step 4, draw the children
8842 dispatchDraw(canvas);
8843
8844 // Step 6, draw decorations (scrollbars)
8845 onDrawScrollBars(canvas);
8846
8847 // we're done...
8848 return;
8849 }
8850
8851 /*
8852 * Here we do the full fledged routine...
8853 * (this is an uncommon case where speed matters less,
8854 * this is why we repeat some of the tests that have been
8855 * done above)
8856 */
8857
8858 boolean drawTop = false;
8859 boolean drawBottom = false;
8860 boolean drawLeft = false;
8861 boolean drawRight = false;
8862
8863 float topFadeStrength = 0.0f;
8864 float bottomFadeStrength = 0.0f;
8865 float leftFadeStrength = 0.0f;
8866 float rightFadeStrength = 0.0f;
8867
8868 // Step 2, save the canvas' layers
8869 int paddingLeft = mPaddingLeft;
8870 int paddingTop = mPaddingTop;
8871
8872 final boolean offsetRequired = isPaddingOffsetRequired();
8873 if (offsetRequired) {
8874 paddingLeft += getLeftPaddingOffset();
8875 paddingTop += getTopPaddingOffset();
8876 }
8877
8878 int left = mScrollX + paddingLeft;
8879 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8880 int top = mScrollY + paddingTop;
8881 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8882
8883 if (offsetRequired) {
8884 right += getRightPaddingOffset();
8885 bottom += getBottomPaddingOffset();
8886 }
8887
8888 final ScrollabilityCache scrollabilityCache = mScrollCache;
8889 int length = scrollabilityCache.fadingEdgeLength;
8890
8891 // clip the fade length if top and bottom fades overlap
8892 // overlapping fades produce odd-looking artifacts
8893 if (verticalEdges && (top + length > bottom - length)) {
8894 length = (bottom - top) / 2;
8895 }
8896
8897 // also clip horizontal fades if necessary
8898 if (horizontalEdges && (left + length > right - length)) {
8899 length = (right - left) / 2;
8900 }
8901
8902 if (verticalEdges) {
8903 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008904 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008905 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008906 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008907 }
8908
8909 if (horizontalEdges) {
8910 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008911 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008912 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07008913 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008914 }
8915
8916 saveCount = canvas.getSaveCount();
8917
8918 int solidColor = getSolidColor();
Romain Guyf607bdc2010-09-10 19:20:06 -07008919 if (solidColor == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008920 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8921
8922 if (drawTop) {
8923 canvas.saveLayer(left, top, right, top + length, null, flags);
8924 }
8925
8926 if (drawBottom) {
8927 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8928 }
8929
8930 if (drawLeft) {
8931 canvas.saveLayer(left, top, left + length, bottom, null, flags);
8932 }
8933
8934 if (drawRight) {
8935 canvas.saveLayer(right - length, top, right, bottom, null, flags);
8936 }
8937 } else {
8938 scrollabilityCache.setFadeColor(solidColor);
8939 }
8940
8941 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07008942 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943
8944 // Step 4, draw the children
8945 dispatchDraw(canvas);
8946
8947 // Step 5, draw the fade effect and restore layers
8948 final Paint p = scrollabilityCache.paint;
8949 final Matrix matrix = scrollabilityCache.matrix;
8950 final Shader fade = scrollabilityCache.shader;
8951 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8952
8953 if (drawTop) {
8954 matrix.setScale(1, fadeHeight * topFadeStrength);
8955 matrix.postTranslate(left, top);
8956 fade.setLocalMatrix(matrix);
8957 canvas.drawRect(left, top, right, top + length, p);
8958 }
8959
8960 if (drawBottom) {
8961 matrix.setScale(1, fadeHeight * bottomFadeStrength);
8962 matrix.postRotate(180);
8963 matrix.postTranslate(left, bottom);
8964 fade.setLocalMatrix(matrix);
8965 canvas.drawRect(left, bottom - length, right, bottom, p);
8966 }
8967
8968 if (drawLeft) {
8969 matrix.setScale(1, fadeHeight * leftFadeStrength);
8970 matrix.postRotate(-90);
8971 matrix.postTranslate(left, top);
8972 fade.setLocalMatrix(matrix);
8973 canvas.drawRect(left, top, left + length, bottom, p);
8974 }
8975
8976 if (drawRight) {
8977 matrix.setScale(1, fadeHeight * rightFadeStrength);
8978 matrix.postRotate(90);
8979 matrix.postTranslate(right, top);
8980 fade.setLocalMatrix(matrix);
8981 canvas.drawRect(right - length, top, right, bottom, p);
8982 }
8983
8984 canvas.restoreToCount(saveCount);
8985
8986 // Step 6, draw decorations (scrollbars)
8987 onDrawScrollBars(canvas);
8988 }
8989
8990 /**
8991 * Override this if your view is known to always be drawn on top of a solid color background,
8992 * and needs to draw fading edges. Returning a non-zero color enables the view system to
8993 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8994 * should be set to 0xFF.
8995 *
8996 * @see #setVerticalFadingEdgeEnabled
8997 * @see #setHorizontalFadingEdgeEnabled
8998 *
8999 * @return The known solid color background for this view, or 0 if the color may vary
9000 */
9001 public int getSolidColor() {
9002 return 0;
9003 }
9004
9005 /**
9006 * Build a human readable string representation of the specified view flags.
9007 *
9008 * @param flags the view flags to convert to a string
9009 * @return a String representing the supplied flags
9010 */
9011 private static String printFlags(int flags) {
9012 String output = "";
9013 int numFlags = 0;
9014 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
9015 output += "TAKES_FOCUS";
9016 numFlags++;
9017 }
9018
9019 switch (flags & VISIBILITY_MASK) {
9020 case INVISIBLE:
9021 if (numFlags > 0) {
9022 output += " ";
9023 }
9024 output += "INVISIBLE";
9025 // USELESS HERE numFlags++;
9026 break;
9027 case GONE:
9028 if (numFlags > 0) {
9029 output += " ";
9030 }
9031 output += "GONE";
9032 // USELESS HERE numFlags++;
9033 break;
9034 default:
9035 break;
9036 }
9037 return output;
9038 }
9039
9040 /**
9041 * Build a human readable string representation of the specified private
9042 * view flags.
9043 *
9044 * @param privateFlags the private view flags to convert to a string
9045 * @return a String representing the supplied flags
9046 */
9047 private static String printPrivateFlags(int privateFlags) {
9048 String output = "";
9049 int numFlags = 0;
9050
9051 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
9052 output += "WANTS_FOCUS";
9053 numFlags++;
9054 }
9055
9056 if ((privateFlags & FOCUSED) == FOCUSED) {
9057 if (numFlags > 0) {
9058 output += " ";
9059 }
9060 output += "FOCUSED";
9061 numFlags++;
9062 }
9063
9064 if ((privateFlags & SELECTED) == SELECTED) {
9065 if (numFlags > 0) {
9066 output += " ";
9067 }
9068 output += "SELECTED";
9069 numFlags++;
9070 }
9071
9072 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
9073 if (numFlags > 0) {
9074 output += " ";
9075 }
9076 output += "IS_ROOT_NAMESPACE";
9077 numFlags++;
9078 }
9079
9080 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
9081 if (numFlags > 0) {
9082 output += " ";
9083 }
9084 output += "HAS_BOUNDS";
9085 numFlags++;
9086 }
9087
9088 if ((privateFlags & DRAWN) == DRAWN) {
9089 if (numFlags > 0) {
9090 output += " ";
9091 }
9092 output += "DRAWN";
9093 // USELESS HERE numFlags++;
9094 }
9095 return output;
9096 }
9097
9098 /**
9099 * <p>Indicates whether or not this view's layout will be requested during
9100 * the next hierarchy layout pass.</p>
9101 *
9102 * @return true if the layout will be forced during next layout pass
9103 */
9104 public boolean isLayoutRequested() {
9105 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
9106 }
9107
9108 /**
9109 * Assign a size and position to a view and all of its
9110 * descendants
9111 *
9112 * <p>This is the second phase of the layout mechanism.
9113 * (The first is measuring). In this phase, each parent calls
9114 * layout on all of its children to position them.
9115 * This is typically done using the child measurements
Chet Haase9c087442011-01-12 16:20:16 -08009116 * that were stored in the measure pass().</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009117 *
Chet Haase9c087442011-01-12 16:20:16 -08009118 * <p>Derived classes should not override this method.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009119 * Derived classes with children should override
9120 * onLayout. In that method, they should
Chet Haase9c087442011-01-12 16:20:16 -08009121 * call layout on each of their children.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009122 *
9123 * @param l Left position, relative to parent
9124 * @param t Top position, relative to parent
9125 * @param r Right position, relative to parent
9126 * @param b Bottom position, relative to parent
9127 */
Romain Guy5429e1d2010-09-07 12:38:00 -07009128 @SuppressWarnings({"unchecked"})
Chet Haase9c087442011-01-12 16:20:16 -08009129 public void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07009130 int oldL = mLeft;
9131 int oldT = mTop;
9132 int oldB = mBottom;
9133 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009134 boolean changed = setFrame(l, t, r, b);
9135 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
9136 if (ViewDebug.TRACE_HIERARCHY) {
9137 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
9138 }
9139
9140 onLayout(changed, l, t, r, b);
9141 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07009142
9143 if (mOnLayoutChangeListeners != null) {
9144 ArrayList<OnLayoutChangeListener> listenersCopy =
9145 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
9146 int numListeners = listenersCopy.size();
9147 for (int i = 0; i < numListeners; ++i) {
Chet Haase7c608f22010-10-22 17:54:04 -07009148 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
Chet Haase21cd1382010-09-01 17:42:29 -07009149 }
9150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009151 }
9152 mPrivateFlags &= ~FORCE_LAYOUT;
9153 }
9154
9155 /**
9156 * Called from layout when this view should
9157 * assign a size and position to each of its children.
9158 *
9159 * Derived classes with children should override
9160 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07009161 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009162 * @param changed This is a new size or position for this view
9163 * @param left Left position, relative to parent
9164 * @param top Top position, relative to parent
9165 * @param right Right position, relative to parent
9166 * @param bottom Bottom position, relative to parent
9167 */
9168 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
9169 }
9170
9171 /**
9172 * Assign a size and position to this view.
9173 *
9174 * This is called from layout.
9175 *
9176 * @param left Left position, relative to parent
9177 * @param top Top position, relative to parent
9178 * @param right Right position, relative to parent
9179 * @param bottom Bottom position, relative to parent
9180 * @return true if the new size and position are different than the
9181 * previous ones
9182 * {@hide}
9183 */
9184 protected boolean setFrame(int left, int top, int right, int bottom) {
9185 boolean changed = false;
9186
9187 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07009188 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009189 + right + "," + bottom + ")");
9190 }
9191
9192 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
9193 changed = true;
9194
9195 // Remember our drawn bit
9196 int drawn = mPrivateFlags & DRAWN;
9197
9198 // Invalidate our old position
Romain Guy0fd89bf2011-01-26 15:41:30 -08009199 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009200
9201
9202 int oldWidth = mRight - mLeft;
9203 int oldHeight = mBottom - mTop;
9204
9205 mLeft = left;
9206 mTop = top;
9207 mRight = right;
9208 mBottom = bottom;
9209
9210 mPrivateFlags |= HAS_BOUNDS;
9211
9212 int newWidth = right - left;
9213 int newHeight = bottom - top;
9214
9215 if (newWidth != oldWidth || newHeight != oldHeight) {
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009216 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9217 // A change in dimension means an auto-centered pivot point changes, too
9218 mMatrixDirty = true;
9219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009220 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
9221 }
9222
9223 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
9224 // If we are visible, force the DRAWN bit to on so that
9225 // this invalidate will go through (at least to our parent).
9226 // This is because someone may have invalidated this view
Chet Haase6c7ad5d2010-12-28 08:40:00 -08009227 // before this call to setFrame came in, thereby clearing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009228 // the DRAWN bit.
9229 mPrivateFlags |= DRAWN;
Romain Guy0fd89bf2011-01-26 15:41:30 -08009230 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009231 }
9232
9233 // Reset drawn bit to original value (invalidate turns it off)
9234 mPrivateFlags |= drawn;
9235
9236 mBackgroundSizeChanged = true;
9237 }
9238 return changed;
9239 }
9240
9241 /**
9242 * Finalize inflating a view from XML. This is called as the last phase
9243 * of inflation, after all child views have been added.
9244 *
9245 * <p>Even if the subclass overrides onFinishInflate, they should always be
9246 * sure to call the super method, so that we get called.
9247 */
9248 protected void onFinishInflate() {
9249 }
9250
9251 /**
9252 * Returns the resources associated with this view.
9253 *
9254 * @return Resources object.
9255 */
9256 public Resources getResources() {
9257 return mResources;
9258 }
9259
9260 /**
9261 * Invalidates the specified Drawable.
9262 *
9263 * @param drawable the drawable to invalidate
9264 */
9265 public void invalidateDrawable(Drawable drawable) {
9266 if (verifyDrawable(drawable)) {
9267 final Rect dirty = drawable.getBounds();
9268 final int scrollX = mScrollX;
9269 final int scrollY = mScrollY;
9270
9271 invalidate(dirty.left + scrollX, dirty.top + scrollY,
9272 dirty.right + scrollX, dirty.bottom + scrollY);
9273 }
9274 }
9275
9276 /**
9277 * Schedules an action on a drawable to occur at a specified time.
9278 *
9279 * @param who the recipient of the action
9280 * @param what the action to run on the drawable
9281 * @param when the time at which the action must occur. Uses the
9282 * {@link SystemClock#uptimeMillis} timebase.
9283 */
9284 public void scheduleDrawable(Drawable who, Runnable what, long when) {
9285 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9286 mAttachInfo.mHandler.postAtTime(what, who, when);
9287 }
9288 }
9289
9290 /**
9291 * Cancels a scheduled action on a drawable.
9292 *
9293 * @param who the recipient of the action
9294 * @param what the action to cancel
9295 */
9296 public void unscheduleDrawable(Drawable who, Runnable what) {
9297 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9298 mAttachInfo.mHandler.removeCallbacks(what, who);
9299 }
9300 }
9301
9302 /**
9303 * Unschedule any events associated with the given Drawable. This can be
9304 * used when selecting a new Drawable into a view, so that the previous
9305 * one is completely unscheduled.
9306 *
9307 * @param who The Drawable to unschedule.
9308 *
9309 * @see #drawableStateChanged
9310 */
9311 public void unscheduleDrawable(Drawable who) {
9312 if (mAttachInfo != null) {
9313 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
9314 }
9315 }
9316
9317 /**
9318 * If your view subclass is displaying its own Drawable objects, it should
9319 * override this function and return true for any Drawable it is
9320 * displaying. This allows animations for those drawables to be
9321 * scheduled.
9322 *
9323 * <p>Be sure to call through to the super class when overriding this
9324 * function.
9325 *
9326 * @param who The Drawable to verify. Return true if it is one you are
9327 * displaying, else return the result of calling through to the
9328 * super class.
9329 *
9330 * @return boolean If true than the Drawable is being displayed in the
9331 * view; else false and it is not allowed to animate.
9332 *
9333 * @see #unscheduleDrawable
9334 * @see #drawableStateChanged
9335 */
9336 protected boolean verifyDrawable(Drawable who) {
9337 return who == mBGDrawable;
9338 }
9339
9340 /**
9341 * This function is called whenever the state of the view changes in such
9342 * a way that it impacts the state of drawables being shown.
9343 *
9344 * <p>Be sure to call through to the superclass when overriding this
9345 * function.
9346 *
9347 * @see Drawable#setState
9348 */
9349 protected void drawableStateChanged() {
9350 Drawable d = mBGDrawable;
9351 if (d != null && d.isStateful()) {
9352 d.setState(getDrawableState());
9353 }
9354 }
9355
9356 /**
9357 * Call this to force a view to update its drawable state. This will cause
9358 * drawableStateChanged to be called on this view. Views that are interested
9359 * in the new state should call getDrawableState.
9360 *
9361 * @see #drawableStateChanged
9362 * @see #getDrawableState
9363 */
9364 public void refreshDrawableState() {
9365 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9366 drawableStateChanged();
9367
9368 ViewParent parent = mParent;
9369 if (parent != null) {
9370 parent.childDrawableStateChanged(this);
9371 }
9372 }
9373
9374 /**
9375 * Return an array of resource IDs of the drawable states representing the
9376 * current state of the view.
9377 *
9378 * @return The current drawable state
9379 *
9380 * @see Drawable#setState
9381 * @see #drawableStateChanged
9382 * @see #onCreateDrawableState
9383 */
9384 public final int[] getDrawableState() {
9385 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
9386 return mDrawableState;
9387 } else {
9388 mDrawableState = onCreateDrawableState(0);
9389 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
9390 return mDrawableState;
9391 }
9392 }
9393
9394 /**
9395 * Generate the new {@link android.graphics.drawable.Drawable} state for
9396 * this view. This is called by the view
9397 * system when the cached Drawable state is determined to be invalid. To
9398 * retrieve the current state, you should use {@link #getDrawableState}.
9399 *
9400 * @param extraSpace if non-zero, this is the number of extra entries you
9401 * would like in the returned array in which you can place your own
9402 * states.
9403 *
9404 * @return Returns an array holding the current {@link Drawable} state of
9405 * the view.
9406 *
9407 * @see #mergeDrawableStates
9408 */
9409 protected int[] onCreateDrawableState(int extraSpace) {
9410 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
9411 mParent instanceof View) {
9412 return ((View) mParent).onCreateDrawableState(extraSpace);
9413 }
9414
9415 int[] drawableState;
9416
9417 int privateFlags = mPrivateFlags;
9418
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009419 int viewStateIndex = 0;
9420 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
9421 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
9422 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
Neel Parekhe5378582010-10-06 11:36:50 -07009423 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009424 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
9425 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08009426 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
9427 // This is set if HW acceleration is requested, even if the current
9428 // process doesn't allow it. This is just to allow app preview
9429 // windows to better match their app.
9430 viewStateIndex |= VIEW_STATE_ACCELERATED;
9431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009432
9433 drawableState = VIEW_STATE_SETS[viewStateIndex];
9434
9435 //noinspection ConstantIfStatement
9436 if (false) {
9437 Log.i("View", "drawableStateIndex=" + viewStateIndex);
9438 Log.i("View", toString()
9439 + " pressed=" + ((privateFlags & PRESSED) != 0)
9440 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
9441 + " fo=" + hasFocus()
9442 + " sl=" + ((privateFlags & SELECTED) != 0)
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009443 + " wf=" + hasWindowFocus()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009444 + ": " + Arrays.toString(drawableState));
9445 }
9446
9447 if (extraSpace == 0) {
9448 return drawableState;
9449 }
9450
9451 final int[] fullState;
9452 if (drawableState != null) {
9453 fullState = new int[drawableState.length + extraSpace];
9454 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
9455 } else {
9456 fullState = new int[extraSpace];
9457 }
9458
9459 return fullState;
9460 }
9461
9462 /**
9463 * Merge your own state values in <var>additionalState</var> into the base
9464 * state values <var>baseState</var> that were returned by
9465 * {@link #onCreateDrawableState}.
9466 *
9467 * @param baseState The base state values returned by
9468 * {@link #onCreateDrawableState}, which will be modified to also hold your
9469 * own additional state values.
9470 *
9471 * @param additionalState The additional state values you would like
9472 * added to <var>baseState</var>; this array is not modified.
9473 *
9474 * @return As a convenience, the <var>baseState</var> array you originally
9475 * passed into the function is returned.
9476 *
9477 * @see #onCreateDrawableState
9478 */
9479 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
9480 final int N = baseState.length;
9481 int i = N - 1;
9482 while (i >= 0 && baseState[i] == 0) {
9483 i--;
9484 }
9485 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
9486 return baseState;
9487 }
9488
9489 /**
Dianne Hackborn079e2352010-10-18 17:02:43 -07009490 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
9491 * on all Drawable objects associated with this view.
9492 */
9493 public void jumpDrawablesToCurrentState() {
9494 if (mBGDrawable != null) {
9495 mBGDrawable.jumpToCurrentState();
9496 }
9497 }
9498
9499 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009500 * Sets the background color for this view.
9501 * @param color the color of the background
9502 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009503 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009504 public void setBackgroundColor(int color) {
Chet Haase70d4ba12010-10-06 09:46:45 -07009505 if (mBGDrawable instanceof ColorDrawable) {
9506 ((ColorDrawable) mBGDrawable).setColor(color);
9507 } else {
9508 setBackgroundDrawable(new ColorDrawable(color));
9509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009510 }
9511
9512 /**
9513 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07009514 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009515 * @param resid The identifier of the resource.
9516 * @attr ref android.R.styleable#View_background
9517 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00009518 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009519 public void setBackgroundResource(int resid) {
9520 if (resid != 0 && resid == mBackgroundResource) {
9521 return;
9522 }
9523
9524 Drawable d= null;
9525 if (resid != 0) {
9526 d = mResources.getDrawable(resid);
9527 }
9528 setBackgroundDrawable(d);
9529
9530 mBackgroundResource = resid;
9531 }
9532
9533 /**
9534 * Set the background to a given Drawable, or remove the background. If the
9535 * background has padding, this View's padding is set to the background's
9536 * padding. However, when a background is removed, this View's padding isn't
9537 * touched. If setting the padding is desired, please use
9538 * {@link #setPadding(int, int, int, int)}.
9539 *
9540 * @param d The Drawable to use as the background, or null to remove the
9541 * background
9542 */
9543 public void setBackgroundDrawable(Drawable d) {
9544 boolean requestLayout = false;
9545
9546 mBackgroundResource = 0;
9547
9548 /*
9549 * Regardless of whether we're setting a new background or not, we want
9550 * to clear the previous drawable.
9551 */
9552 if (mBGDrawable != null) {
9553 mBGDrawable.setCallback(null);
9554 unscheduleDrawable(mBGDrawable);
9555 }
9556
9557 if (d != null) {
9558 Rect padding = sThreadLocal.get();
9559 if (padding == null) {
9560 padding = new Rect();
9561 sThreadLocal.set(padding);
9562 }
9563 if (d.getPadding(padding)) {
9564 setPadding(padding.left, padding.top, padding.right, padding.bottom);
9565 }
9566
9567 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
9568 // if it has a different minimum size, we should layout again
9569 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
9570 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
9571 requestLayout = true;
9572 }
9573
9574 d.setCallback(this);
9575 if (d.isStateful()) {
9576 d.setState(getDrawableState());
9577 }
9578 d.setVisible(getVisibility() == VISIBLE, false);
9579 mBGDrawable = d;
9580
9581 if ((mPrivateFlags & SKIP_DRAW) != 0) {
9582 mPrivateFlags &= ~SKIP_DRAW;
9583 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
9584 requestLayout = true;
9585 }
9586 } else {
9587 /* Remove the background */
9588 mBGDrawable = null;
9589
9590 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
9591 /*
9592 * This view ONLY drew the background before and we're removing
9593 * the background, so now it won't draw anything
9594 * (hence we SKIP_DRAW)
9595 */
9596 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
9597 mPrivateFlags |= SKIP_DRAW;
9598 }
9599
9600 /*
9601 * When the background is set, we try to apply its padding to this
9602 * View. When the background is removed, we don't touch this View's
9603 * padding. This is noted in the Javadocs. Hence, we don't need to
9604 * requestLayout(), the invalidate() below is sufficient.
9605 */
9606
9607 // The old background's minimum size could have affected this
9608 // View's layout, so let's requestLayout
9609 requestLayout = true;
9610 }
9611
Romain Guy8f1344f52009-05-15 16:03:59 -07009612 computeOpaqueFlags();
9613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009614 if (requestLayout) {
9615 requestLayout();
9616 }
9617
9618 mBackgroundSizeChanged = true;
Romain Guy0fd89bf2011-01-26 15:41:30 -08009619 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009620 }
9621
9622 /**
9623 * Gets the background drawable
9624 * @return The drawable used as the background for this view, if any.
9625 */
9626 public Drawable getBackground() {
9627 return mBGDrawable;
9628 }
9629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009630 /**
9631 * Sets the padding. The view may add on the space required to display
9632 * the scrollbars, depending on the style and visibility of the scrollbars.
9633 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
9634 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
9635 * from the values set in this call.
9636 *
9637 * @attr ref android.R.styleable#View_padding
9638 * @attr ref android.R.styleable#View_paddingBottom
9639 * @attr ref android.R.styleable#View_paddingLeft
9640 * @attr ref android.R.styleable#View_paddingRight
9641 * @attr ref android.R.styleable#View_paddingTop
9642 * @param left the left padding in pixels
9643 * @param top the top padding in pixels
9644 * @param right the right padding in pixels
9645 * @param bottom the bottom padding in pixels
9646 */
9647 public void setPadding(int left, int top, int right, int bottom) {
9648 boolean changed = false;
9649
Adam Powell20232d02010-12-08 21:08:53 -08009650 mUserPaddingLeft = left;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009651 mUserPaddingRight = right;
9652 mUserPaddingBottom = bottom;
9653
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009654 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07009655
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009656 // Common case is there are no scroll bars.
9657 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009658 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
Adam Powell20232d02010-12-08 21:08:53 -08009659 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
9660 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009661 ? 0 : getVerticalScrollbarWidth();
Adam Powell20232d02010-12-08 21:08:53 -08009662 switch (mVerticalScrollbarPosition) {
9663 case SCROLLBAR_POSITION_DEFAULT:
9664 case SCROLLBAR_POSITION_RIGHT:
9665 right += offset;
9666 break;
9667 case SCROLLBAR_POSITION_LEFT:
9668 left += offset;
9669 break;
9670 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009671 }
Adam Powell20232d02010-12-08 21:08:53 -08009672 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009673 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9674 ? 0 : getHorizontalScrollbarHeight();
9675 }
9676 }
Romain Guy8506ab42009-06-11 17:35:47 -07009677
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009678 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 changed = true;
9680 mPaddingLeft = left;
9681 }
9682 if (mPaddingTop != top) {
9683 changed = true;
9684 mPaddingTop = top;
9685 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009686 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009687 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009688 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009689 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009690 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009691 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07009692 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009693 }
9694
9695 if (changed) {
9696 requestLayout();
9697 }
9698 }
9699
9700 /**
9701 * Returns the top padding of this view.
9702 *
9703 * @return the top padding in pixels
9704 */
9705 public int getPaddingTop() {
9706 return mPaddingTop;
9707 }
9708
9709 /**
9710 * Returns the bottom padding of this view. If there are inset and enabled
9711 * scrollbars, this value may include the space required to display the
9712 * scrollbars as well.
9713 *
9714 * @return the bottom padding in pixels
9715 */
9716 public int getPaddingBottom() {
9717 return mPaddingBottom;
9718 }
9719
9720 /**
9721 * Returns the left padding of this view. If there are inset and enabled
9722 * scrollbars, this value may include the space required to display the
9723 * scrollbars as well.
9724 *
9725 * @return the left padding in pixels
9726 */
9727 public int getPaddingLeft() {
9728 return mPaddingLeft;
9729 }
9730
9731 /**
9732 * Returns the right padding of this view. If there are inset and enabled
9733 * scrollbars, this value may include the space required to display the
9734 * scrollbars as well.
9735 *
9736 * @return the right padding in pixels
9737 */
9738 public int getPaddingRight() {
9739 return mPaddingRight;
9740 }
9741
9742 /**
9743 * Changes the selection state of this view. A view can be selected or not.
9744 * Note that selection is not the same as focus. Views are typically
9745 * selected in the context of an AdapterView like ListView or GridView;
9746 * the selected view is the view that is highlighted.
9747 *
9748 * @param selected true if the view must be selected, false otherwise
9749 */
9750 public void setSelected(boolean selected) {
9751 if (((mPrivateFlags & SELECTED) != 0) != selected) {
9752 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07009753 if (!selected) resetPressedState();
Romain Guy0fd89bf2011-01-26 15:41:30 -08009754 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009755 refreshDrawableState();
9756 dispatchSetSelected(selected);
9757 }
9758 }
9759
9760 /**
9761 * Dispatch setSelected to all of this View's children.
9762 *
9763 * @see #setSelected(boolean)
9764 *
9765 * @param selected The new selected state
9766 */
9767 protected void dispatchSetSelected(boolean selected) {
9768 }
9769
9770 /**
9771 * Indicates the selection state of this view.
9772 *
9773 * @return true if the view is selected, false otherwise
9774 */
9775 @ViewDebug.ExportedProperty
9776 public boolean isSelected() {
9777 return (mPrivateFlags & SELECTED) != 0;
9778 }
9779
9780 /**
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009781 * Changes the activated state of this view. A view can be activated or not.
9782 * Note that activation is not the same as selection. Selection is
9783 * a transient property, representing the view (hierarchy) the user is
9784 * currently interacting with. Activation is a longer-term state that the
9785 * user can move views in and out of. For example, in a list view with
9786 * single or multiple selection enabled, the views in the current selection
9787 * set are activated. (Um, yeah, we are deeply sorry about the terminology
9788 * here.) The activated state is propagated down to children of the view it
9789 * is set on.
9790 *
9791 * @param activated true if the view must be activated, false otherwise
9792 */
9793 public void setActivated(boolean activated) {
9794 if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9795 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
Romain Guy0fd89bf2011-01-26 15:41:30 -08009796 invalidate(true);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009797 refreshDrawableState();
Dianne Hackbornc6669ca2010-09-16 01:33:24 -07009798 dispatchSetActivated(activated);
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07009799 }
9800 }
9801
9802 /**
9803 * Dispatch setActivated to all of this View's children.
9804 *
9805 * @see #setActivated(boolean)
9806 *
9807 * @param activated The new activated state
9808 */
9809 protected void dispatchSetActivated(boolean activated) {
9810 }
9811
9812 /**
9813 * Indicates the activation state of this view.
9814 *
9815 * @return true if the view is activated, false otherwise
9816 */
9817 @ViewDebug.ExportedProperty
9818 public boolean isActivated() {
9819 return (mPrivateFlags & ACTIVATED) != 0;
9820 }
9821
9822 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009823 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9824 * observer can be used to get notifications when global events, like
9825 * layout, happen.
9826 *
9827 * The returned ViewTreeObserver observer is not guaranteed to remain
9828 * valid for the lifetime of this View. If the caller of this method keeps
9829 * a long-lived reference to ViewTreeObserver, it should always check for
9830 * the return value of {@link ViewTreeObserver#isAlive()}.
9831 *
9832 * @return The ViewTreeObserver for this view's hierarchy.
9833 */
9834 public ViewTreeObserver getViewTreeObserver() {
9835 if (mAttachInfo != null) {
9836 return mAttachInfo.mTreeObserver;
9837 }
9838 if (mFloatingTreeObserver == null) {
9839 mFloatingTreeObserver = new ViewTreeObserver();
9840 }
9841 return mFloatingTreeObserver;
9842 }
9843
9844 /**
9845 * <p>Finds the topmost view in the current view hierarchy.</p>
9846 *
9847 * @return the topmost view containing this view
9848 */
9849 public View getRootView() {
9850 if (mAttachInfo != null) {
9851 final View v = mAttachInfo.mRootView;
9852 if (v != null) {
9853 return v;
9854 }
9855 }
Romain Guy8506ab42009-06-11 17:35:47 -07009856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009857 View parent = this;
9858
9859 while (parent.mParent != null && parent.mParent instanceof View) {
9860 parent = (View) parent.mParent;
9861 }
9862
9863 return parent;
9864 }
9865
9866 /**
9867 * <p>Computes the coordinates of this view on the screen. The argument
9868 * must be an array of two integers. After the method returns, the array
9869 * contains the x and y location in that order.</p>
9870 *
9871 * @param location an array of two integers in which to hold the coordinates
9872 */
9873 public void getLocationOnScreen(int[] location) {
9874 getLocationInWindow(location);
9875
9876 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07009877 if (info != null) {
9878 location[0] += info.mWindowLeft;
9879 location[1] += info.mWindowTop;
9880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009881 }
9882
9883 /**
9884 * <p>Computes the coordinates of this view in its window. The argument
9885 * must be an array of two integers. After the method returns, the array
9886 * contains the x and y location in that order.</p>
9887 *
9888 * @param location an array of two integers in which to hold the coordinates
9889 */
9890 public void getLocationInWindow(int[] location) {
9891 if (location == null || location.length < 2) {
9892 throw new IllegalArgumentException("location must be an array of "
9893 + "two integers");
9894 }
9895
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009896 location[0] = mLeft + (int) (mTranslationX + 0.5f);
9897 location[1] = mTop + (int) (mTranslationY + 0.5f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009898
9899 ViewParent viewParent = mParent;
9900 while (viewParent instanceof View) {
9901 final View view = (View)viewParent;
Michael Jurka4d2bd4c2010-11-30 18:15:11 -08009902 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
9903 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009904 viewParent = view.mParent;
9905 }
Romain Guy8506ab42009-06-11 17:35:47 -07009906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009907 if (viewParent instanceof ViewRoot) {
9908 // *cough*
9909 final ViewRoot vr = (ViewRoot)viewParent;
9910 location[1] -= vr.mCurScrollY;
9911 }
9912 }
9913
9914 /**
9915 * {@hide}
9916 * @param id the id of the view to be found
9917 * @return the view of the specified id, null if cannot be found
9918 */
9919 protected View findViewTraversal(int id) {
9920 if (id == mID) {
9921 return this;
9922 }
9923 return null;
9924 }
9925
9926 /**
9927 * {@hide}
9928 * @param tag the tag of the view to be found
9929 * @return the view of specified tag, null if cannot be found
9930 */
9931 protected View findViewWithTagTraversal(Object tag) {
9932 if (tag != null && tag.equals(mTag)) {
9933 return this;
9934 }
9935 return null;
9936 }
9937
9938 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009939 * {@hide}
9940 * @param predicate The predicate to evaluate.
9941 * @return The first view that matches the predicate or null.
9942 */
9943 protected View findViewByPredicateTraversal(Predicate<View> predicate) {
9944 if (predicate.apply(this)) {
9945 return this;
9946 }
9947 return null;
9948 }
9949
9950 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009951 * Look for a child view with the given id. If this view has the given
9952 * id, return this view.
9953 *
9954 * @param id The id to search for.
9955 * @return The view that has the given id in the hierarchy or null
9956 */
9957 public final View findViewById(int id) {
9958 if (id < 0) {
9959 return null;
9960 }
9961 return findViewTraversal(id);
9962 }
9963
9964 /**
9965 * Look for a child view with the given tag. If this view has the given
9966 * tag, return this view.
9967 *
9968 * @param tag The tag to search for, using "tag.equals(getTag())".
9969 * @return The View that has the given tag in the hierarchy or null
9970 */
9971 public final View findViewWithTag(Object tag) {
9972 if (tag == null) {
9973 return null;
9974 }
9975 return findViewWithTagTraversal(tag);
9976 }
9977
9978 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08009979 * {@hide}
9980 * Look for a child view that matches the specified predicate.
9981 * If this view matches the predicate, return this view.
9982 *
9983 * @param predicate The predicate to evaluate.
9984 * @return The first view that matches the predicate or null.
9985 */
9986 public final View findViewByPredicate(Predicate<View> predicate) {
9987 return findViewByPredicateTraversal(predicate);
9988 }
9989
9990 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009991 * Sets the identifier for this view. The identifier does not have to be
9992 * unique in this view's hierarchy. The identifier should be a positive
9993 * number.
9994 *
9995 * @see #NO_ID
9996 * @see #getId
9997 * @see #findViewById
9998 *
9999 * @param id a number used to identify the view
10000 *
10001 * @attr ref android.R.styleable#View_id
10002 */
10003 public void setId(int id) {
10004 mID = id;
10005 }
10006
10007 /**
10008 * {@hide}
10009 *
10010 * @param isRoot true if the view belongs to the root namespace, false
10011 * otherwise
10012 */
10013 public void setIsRootNamespace(boolean isRoot) {
10014 if (isRoot) {
10015 mPrivateFlags |= IS_ROOT_NAMESPACE;
10016 } else {
10017 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
10018 }
10019 }
10020
10021 /**
10022 * {@hide}
10023 *
10024 * @return true if the view belongs to the root namespace, false otherwise
10025 */
10026 public boolean isRootNamespace() {
10027 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
10028 }
10029
10030 /**
10031 * Returns this view's identifier.
10032 *
10033 * @return a positive integer used to identify the view or {@link #NO_ID}
10034 * if the view has no ID
10035 *
10036 * @see #setId
10037 * @see #findViewById
10038 * @attr ref android.R.styleable#View_id
10039 */
10040 @ViewDebug.CapturedViewProperty
10041 public int getId() {
10042 return mID;
10043 }
10044
10045 /**
10046 * Returns this view's tag.
10047 *
10048 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -070010049 *
10050 * @see #setTag(Object)
10051 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010052 */
10053 @ViewDebug.ExportedProperty
10054 public Object getTag() {
10055 return mTag;
10056 }
10057
10058 /**
10059 * Sets the tag associated with this view. A tag can be used to mark
10060 * a view in its hierarchy and does not have to be unique within the
10061 * hierarchy. Tags can also be used to store data within a view without
10062 * resorting to another data structure.
10063 *
10064 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -070010065 *
10066 * @see #getTag()
10067 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010068 */
10069 public void setTag(final Object tag) {
10070 mTag = tag;
10071 }
10072
10073 /**
Romain Guyd90a3312009-05-06 14:54:28 -070010074 * Returns the tag associated with this view and the specified key.
10075 *
10076 * @param key The key identifying the tag
10077 *
10078 * @return the Object stored in this view as a tag
10079 *
10080 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -070010081 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -070010082 */
10083 public Object getTag(int key) {
10084 SparseArray<Object> tags = null;
10085 synchronized (sTagsLock) {
10086 if (sTags != null) {
10087 tags = sTags.get(this);
10088 }
10089 }
10090
10091 if (tags != null) return tags.get(key);
10092 return null;
10093 }
10094
10095 /**
10096 * Sets a tag associated with this view and a key. A tag can be used
10097 * to mark a view in its hierarchy and does not have to be unique within
10098 * the hierarchy. Tags can also be used to store data within a view
10099 * without resorting to another data structure.
10100 *
10101 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -070010102 * application to ensure it is unique (see the <a
10103 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
10104 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -070010105 * the Android framework or not associated with any package will cause
10106 * an {@link IllegalArgumentException} to be thrown.
10107 *
10108 * @param key The key identifying the tag
10109 * @param tag An Object to tag the view with
10110 *
10111 * @throws IllegalArgumentException If they specified key is not valid
10112 *
10113 * @see #setTag(Object)
10114 * @see #getTag(int)
10115 */
10116 public void setTag(int key, final Object tag) {
10117 // If the package id is 0x00 or 0x01, it's either an undefined package
10118 // or a framework id
10119 if ((key >>> 24) < 2) {
10120 throw new IllegalArgumentException("The key must be an application-specific "
10121 + "resource id.");
10122 }
10123
10124 setTagInternal(this, key, tag);
10125 }
10126
10127 /**
10128 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
10129 * framework id.
10130 *
10131 * @hide
10132 */
10133 public void setTagInternal(int key, Object tag) {
10134 if ((key >>> 24) != 0x1) {
10135 throw new IllegalArgumentException("The key must be a framework-specific "
10136 + "resource id.");
10137 }
10138
Romain Guy8506ab42009-06-11 17:35:47 -070010139 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -070010140 }
10141
10142 private static void setTagInternal(View view, int key, Object tag) {
10143 SparseArray<Object> tags = null;
10144 synchronized (sTagsLock) {
10145 if (sTags == null) {
10146 sTags = new WeakHashMap<View, SparseArray<Object>>();
10147 } else {
10148 tags = sTags.get(view);
10149 }
10150 }
10151
10152 if (tags == null) {
10153 tags = new SparseArray<Object>(2);
10154 synchronized (sTagsLock) {
10155 sTags.put(view, tags);
10156 }
10157 }
10158
10159 tags.put(key, tag);
10160 }
10161
10162 /**
Romain Guy13922e02009-05-12 17:56:14 -070010163 * @param consistency The type of consistency. See ViewDebug for more information.
10164 *
10165 * @hide
10166 */
10167 protected boolean dispatchConsistencyCheck(int consistency) {
10168 return onConsistencyCheck(consistency);
10169 }
10170
10171 /**
10172 * Method that subclasses should implement to check their consistency. The type of
10173 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -070010174 *
Romain Guy13922e02009-05-12 17:56:14 -070010175 * @param consistency The type of consistency. See ViewDebug for more information.
10176 *
10177 * @throws IllegalStateException if the view is in an inconsistent state.
10178 *
10179 * @hide
10180 */
10181 protected boolean onConsistencyCheck(int consistency) {
10182 boolean result = true;
10183
10184 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
10185 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
10186
10187 if (checkLayout) {
10188 if (getParent() == null) {
10189 result = false;
10190 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10191 "View " + this + " does not have a parent.");
10192 }
10193
10194 if (mAttachInfo == null) {
10195 result = false;
10196 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10197 "View " + this + " is not attached to a window.");
10198 }
10199 }
10200
10201 if (checkDrawing) {
10202 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
10203 // from their draw() method
10204
10205 if ((mPrivateFlags & DRAWN) != DRAWN &&
10206 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
10207 result = false;
10208 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10209 "View " + this + " was invalidated but its drawing cache is valid.");
10210 }
10211 }
10212
10213 return result;
10214 }
10215
10216 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010217 * Prints information about this view in the log output, with the tag
10218 * {@link #VIEW_LOG_TAG}.
10219 *
10220 * @hide
10221 */
10222 public void debug() {
10223 debug(0);
10224 }
10225
10226 /**
10227 * Prints information about this view in the log output, with the tag
10228 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
10229 * indentation defined by the <code>depth</code>.
10230 *
10231 * @param depth the indentation level
10232 *
10233 * @hide
10234 */
10235 protected void debug(int depth) {
10236 String output = debugIndent(depth - 1);
10237
10238 output += "+ " + this;
10239 int id = getId();
10240 if (id != -1) {
10241 output += " (id=" + id + ")";
10242 }
10243 Object tag = getTag();
10244 if (tag != null) {
10245 output += " (tag=" + tag + ")";
10246 }
10247 Log.d(VIEW_LOG_TAG, output);
10248
10249 if ((mPrivateFlags & FOCUSED) != 0) {
10250 output = debugIndent(depth) + " FOCUSED";
10251 Log.d(VIEW_LOG_TAG, output);
10252 }
10253
10254 output = debugIndent(depth);
10255 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
10256 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
10257 + "} ";
10258 Log.d(VIEW_LOG_TAG, output);
10259
10260 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
10261 || mPaddingBottom != 0) {
10262 output = debugIndent(depth);
10263 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
10264 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
10265 Log.d(VIEW_LOG_TAG, output);
10266 }
10267
10268 output = debugIndent(depth);
10269 output += "mMeasureWidth=" + mMeasuredWidth +
10270 " mMeasureHeight=" + mMeasuredHeight;
10271 Log.d(VIEW_LOG_TAG, output);
10272
10273 output = debugIndent(depth);
10274 if (mLayoutParams == null) {
10275 output += "BAD! no layout params";
10276 } else {
10277 output = mLayoutParams.debug(output);
10278 }
10279 Log.d(VIEW_LOG_TAG, output);
10280
10281 output = debugIndent(depth);
10282 output += "flags={";
10283 output += View.printFlags(mViewFlags);
10284 output += "}";
10285 Log.d(VIEW_LOG_TAG, output);
10286
10287 output = debugIndent(depth);
10288 output += "privateFlags={";
10289 output += View.printPrivateFlags(mPrivateFlags);
10290 output += "}";
10291 Log.d(VIEW_LOG_TAG, output);
10292 }
10293
10294 /**
10295 * Creates an string of whitespaces used for indentation.
10296 *
10297 * @param depth the indentation level
10298 * @return a String containing (depth * 2 + 3) * 2 white spaces
10299 *
10300 * @hide
10301 */
10302 protected static String debugIndent(int depth) {
10303 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
10304 for (int i = 0; i < (depth * 2) + 3; i++) {
10305 spaces.append(' ').append(' ');
10306 }
10307 return spaces.toString();
10308 }
10309
10310 /**
10311 * <p>Return the offset of the widget's text baseline from the widget's top
10312 * boundary. If this widget does not support baseline alignment, this
10313 * method returns -1. </p>
10314 *
10315 * @return the offset of the baseline within the widget's bounds or -1
10316 * if baseline alignment is not supported
10317 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -070010318 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010319 public int getBaseline() {
10320 return -1;
10321 }
10322
10323 /**
10324 * Call this when something has changed which has invalidated the
10325 * layout of this view. This will schedule a layout pass of the view
10326 * tree.
10327 */
10328 public void requestLayout() {
10329 if (ViewDebug.TRACE_HIERARCHY) {
10330 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
10331 }
10332
10333 mPrivateFlags |= FORCE_LAYOUT;
Chet Haase5af048c2011-01-24 17:00:32 -080010334 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010335
10336 if (mParent != null && !mParent.isLayoutRequested()) {
10337 mParent.requestLayout();
10338 }
10339 }
10340
10341 /**
10342 * Forces this view to be laid out during the next layout pass.
10343 * This method does not call requestLayout() or forceLayout()
10344 * on the parent.
10345 */
10346 public void forceLayout() {
10347 mPrivateFlags |= FORCE_LAYOUT;
Chet Haase5af048c2011-01-24 17:00:32 -080010348 mPrivateFlags |= INVALIDATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010349 }
10350
10351 /**
10352 * <p>
10353 * This is called to find out how big a view should be. The parent
10354 * supplies constraint information in the width and height parameters.
10355 * </p>
10356 *
10357 * <p>
10358 * The actual mesurement work of a view is performed in
10359 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
10360 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
10361 * </p>
10362 *
10363 *
10364 * @param widthMeasureSpec Horizontal space requirements as imposed by the
10365 * parent
10366 * @param heightMeasureSpec Vertical space requirements as imposed by the
10367 * parent
10368 *
10369 * @see #onMeasure(int, int)
10370 */
10371 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
10372 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
10373 widthMeasureSpec != mOldWidthMeasureSpec ||
10374 heightMeasureSpec != mOldHeightMeasureSpec) {
10375
10376 // first clears the measured dimension flag
10377 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
10378
10379 if (ViewDebug.TRACE_HIERARCHY) {
10380 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
10381 }
10382
10383 // measure ourselves, this should set the measured dimension flag back
10384 onMeasure(widthMeasureSpec, heightMeasureSpec);
10385
10386 // flag not set, setMeasuredDimension() was not invoked, we raise
10387 // an exception to warn the developer
10388 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
10389 throw new IllegalStateException("onMeasure() did not set the"
10390 + " measured dimension by calling"
10391 + " setMeasuredDimension()");
10392 }
10393
10394 mPrivateFlags |= LAYOUT_REQUIRED;
10395 }
10396
10397 mOldWidthMeasureSpec = widthMeasureSpec;
10398 mOldHeightMeasureSpec = heightMeasureSpec;
10399 }
10400
10401 /**
10402 * <p>
10403 * Measure the view and its content to determine the measured width and the
10404 * measured height. This method is invoked by {@link #measure(int, int)} and
10405 * should be overriden by subclasses to provide accurate and efficient
10406 * measurement of their contents.
10407 * </p>
10408 *
10409 * <p>
10410 * <strong>CONTRACT:</strong> When overriding this method, you
10411 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
10412 * measured width and height of this view. Failure to do so will trigger an
10413 * <code>IllegalStateException</code>, thrown by
10414 * {@link #measure(int, int)}. Calling the superclass'
10415 * {@link #onMeasure(int, int)} is a valid use.
10416 * </p>
10417 *
10418 * <p>
10419 * The base class implementation of measure defaults to the background size,
10420 * unless a larger size is allowed by the MeasureSpec. Subclasses should
10421 * override {@link #onMeasure(int, int)} to provide better measurements of
10422 * their content.
10423 * </p>
10424 *
10425 * <p>
10426 * If this method is overridden, it is the subclass's responsibility to make
10427 * sure the measured height and width are at least the view's minimum height
10428 * and width ({@link #getSuggestedMinimumHeight()} and
10429 * {@link #getSuggestedMinimumWidth()}).
10430 * </p>
10431 *
10432 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
10433 * The requirements are encoded with
10434 * {@link android.view.View.MeasureSpec}.
10435 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
10436 * The requirements are encoded with
10437 * {@link android.view.View.MeasureSpec}.
10438 *
10439 * @see #getMeasuredWidth()
10440 * @see #getMeasuredHeight()
10441 * @see #setMeasuredDimension(int, int)
10442 * @see #getSuggestedMinimumHeight()
10443 * @see #getSuggestedMinimumWidth()
10444 * @see android.view.View.MeasureSpec#getMode(int)
10445 * @see android.view.View.MeasureSpec#getSize(int)
10446 */
10447 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
10448 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
10449 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
10450 }
10451
10452 /**
10453 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
10454 * measured width and measured height. Failing to do so will trigger an
10455 * exception at measurement time.</p>
10456 *
Dianne Hackborn189ee182010-12-02 21:48:53 -080010457 * @param measuredWidth The measured width of this view. May be a complex
10458 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10459 * {@link #MEASURED_STATE_TOO_SMALL}.
10460 * @param measuredHeight The measured height of this view. May be a complex
10461 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10462 * {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010463 */
10464 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
10465 mMeasuredWidth = measuredWidth;
10466 mMeasuredHeight = measuredHeight;
10467
10468 mPrivateFlags |= MEASURED_DIMENSION_SET;
10469 }
10470
10471 /**
Dianne Hackborn189ee182010-12-02 21:48:53 -080010472 * Merge two states as returned by {@link #getMeasuredState()}.
10473 * @param curState The current state as returned from a view or the result
10474 * of combining multiple views.
10475 * @param newState The new view state to combine.
10476 * @return Returns a new integer reflecting the combination of the two
10477 * states.
10478 */
10479 public static int combineMeasuredStates(int curState, int newState) {
10480 return curState | newState;
10481 }
10482
10483 /**
10484 * Version of {@link #resolveSizeAndState(int, int, int)}
10485 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
10486 */
10487 public static int resolveSize(int size, int measureSpec) {
10488 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
10489 }
10490
10491 /**
10492 * Utility to reconcile a desired size and state, with constraints imposed
10493 * by a MeasureSpec. Will take the desired size, unless a different size
10494 * is imposed by the constraints. The returned value is a compound integer,
10495 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
10496 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
10497 * size is smaller than the size the view wants to be.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010498 *
10499 * @param size How big the view wants to be
10500 * @param measureSpec Constraints imposed by the parent
Dianne Hackborn189ee182010-12-02 21:48:53 -080010501 * @return Size information bit mask as defined by
10502 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010503 */
Dianne Hackborn189ee182010-12-02 21:48:53 -080010504 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010505 int result = size;
10506 int specMode = MeasureSpec.getMode(measureSpec);
10507 int specSize = MeasureSpec.getSize(measureSpec);
10508 switch (specMode) {
10509 case MeasureSpec.UNSPECIFIED:
10510 result = size;
10511 break;
10512 case MeasureSpec.AT_MOST:
Dianne Hackborn189ee182010-12-02 21:48:53 -080010513 if (specSize < size) {
10514 result = specSize | MEASURED_STATE_TOO_SMALL;
10515 } else {
10516 result = size;
10517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010518 break;
10519 case MeasureSpec.EXACTLY:
10520 result = specSize;
10521 break;
10522 }
Dianne Hackborn189ee182010-12-02 21:48:53 -080010523 return result | (childMeasuredState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010524 }
10525
10526 /**
10527 * Utility to return a default size. Uses the supplied size if the
10528 * MeasureSpec imposed no contraints. Will get larger if allowed
10529 * by the MeasureSpec.
10530 *
10531 * @param size Default size for this view
10532 * @param measureSpec Constraints imposed by the parent
10533 * @return The size this view should be.
10534 */
10535 public static int getDefaultSize(int size, int measureSpec) {
10536 int result = size;
10537 int specMode = MeasureSpec.getMode(measureSpec);
10538 int specSize = MeasureSpec.getSize(measureSpec);
10539
10540 switch (specMode) {
10541 case MeasureSpec.UNSPECIFIED:
10542 result = size;
10543 break;
10544 case MeasureSpec.AT_MOST:
10545 case MeasureSpec.EXACTLY:
10546 result = specSize;
10547 break;
10548 }
10549 return result;
10550 }
10551
10552 /**
10553 * Returns the suggested minimum height that the view should use. This
10554 * returns the maximum of the view's minimum height
10555 * and the background's minimum height
10556 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
10557 * <p>
10558 * When being used in {@link #onMeasure(int, int)}, the caller should still
10559 * ensure the returned height is within the requirements of the parent.
10560 *
10561 * @return The suggested minimum height of the view.
10562 */
10563 protected int getSuggestedMinimumHeight() {
10564 int suggestedMinHeight = mMinHeight;
10565
10566 if (mBGDrawable != null) {
10567 final int bgMinHeight = mBGDrawable.getMinimumHeight();
10568 if (suggestedMinHeight < bgMinHeight) {
10569 suggestedMinHeight = bgMinHeight;
10570 }
10571 }
10572
10573 return suggestedMinHeight;
10574 }
10575
10576 /**
10577 * Returns the suggested minimum width that the view should use. This
10578 * returns the maximum of the view's minimum width)
10579 * and the background's minimum width
10580 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
10581 * <p>
10582 * When being used in {@link #onMeasure(int, int)}, the caller should still
10583 * ensure the returned width is within the requirements of the parent.
10584 *
10585 * @return The suggested minimum width of the view.
10586 */
10587 protected int getSuggestedMinimumWidth() {
10588 int suggestedMinWidth = mMinWidth;
10589
10590 if (mBGDrawable != null) {
10591 final int bgMinWidth = mBGDrawable.getMinimumWidth();
10592 if (suggestedMinWidth < bgMinWidth) {
10593 suggestedMinWidth = bgMinWidth;
10594 }
10595 }
10596
10597 return suggestedMinWidth;
10598 }
10599
10600 /**
10601 * Sets the minimum height of the view. It is not guaranteed the view will
10602 * be able to achieve this minimum height (for example, if its parent layout
10603 * constrains it with less available height).
10604 *
10605 * @param minHeight The minimum height the view will try to be.
10606 */
10607 public void setMinimumHeight(int minHeight) {
10608 mMinHeight = minHeight;
10609 }
10610
10611 /**
10612 * Sets the minimum width of the view. It is not guaranteed the view will
10613 * be able to achieve this minimum width (for example, if its parent layout
10614 * constrains it with less available width).
10615 *
10616 * @param minWidth The minimum width the view will try to be.
10617 */
10618 public void setMinimumWidth(int minWidth) {
10619 mMinWidth = minWidth;
10620 }
10621
10622 /**
10623 * Get the animation currently associated with this view.
10624 *
10625 * @return The animation that is currently playing or
10626 * scheduled to play for this view.
10627 */
10628 public Animation getAnimation() {
10629 return mCurrentAnimation;
10630 }
10631
10632 /**
10633 * Start the specified animation now.
10634 *
10635 * @param animation the animation to start now
10636 */
10637 public void startAnimation(Animation animation) {
10638 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
10639 setAnimation(animation);
Romain Guy0fd89bf2011-01-26 15:41:30 -080010640 invalidateParentCaches();
10641 invalidate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010642 }
10643
10644 /**
10645 * Cancels any animations for this view.
10646 */
10647 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -080010648 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -080010649 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -080010650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010651 mCurrentAnimation = null;
Romain Guy0fd89bf2011-01-26 15:41:30 -080010652 invalidateParentIfNeeded();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010653 }
10654
10655 /**
10656 * Sets the next animation to play for this view.
10657 * If you want the animation to play immediately, use
10658 * startAnimation. This method provides allows fine-grained
10659 * control over the start time and invalidation, but you
10660 * must make sure that 1) the animation has a start time set, and
10661 * 2) the view will be invalidated when the animation is supposed to
10662 * start.
10663 *
10664 * @param animation The next animation, or null.
10665 */
10666 public void setAnimation(Animation animation) {
10667 mCurrentAnimation = animation;
10668 if (animation != null) {
10669 animation.reset();
10670 }
10671 }
10672
10673 /**
10674 * Invoked by a parent ViewGroup to notify the start of the animation
10675 * currently associated with this view. If you override this method,
10676 * always call super.onAnimationStart();
10677 *
10678 * @see #setAnimation(android.view.animation.Animation)
10679 * @see #getAnimation()
10680 */
10681 protected void onAnimationStart() {
10682 mPrivateFlags |= ANIMATION_STARTED;
10683 }
10684
10685 /**
10686 * Invoked by a parent ViewGroup to notify the end of the animation
10687 * currently associated with this view. If you override this method,
10688 * always call super.onAnimationEnd();
10689 *
10690 * @see #setAnimation(android.view.animation.Animation)
10691 * @see #getAnimation()
10692 */
10693 protected void onAnimationEnd() {
10694 mPrivateFlags &= ~ANIMATION_STARTED;
10695 }
10696
10697 /**
10698 * Invoked if there is a Transform that involves alpha. Subclass that can
10699 * draw themselves with the specified alpha should return true, and then
10700 * respect that alpha when their onDraw() is called. If this returns false
10701 * then the view may be redirected to draw into an offscreen buffer to
10702 * fulfill the request, which will look fine, but may be slower than if the
10703 * subclass handles it internally. The default implementation returns false.
10704 *
10705 * @param alpha The alpha (0..255) to apply to the view's drawing
10706 * @return true if the view can draw with the specified alpha.
10707 */
10708 protected boolean onSetAlpha(int alpha) {
10709 return false;
10710 }
10711
10712 /**
10713 * This is used by the RootView to perform an optimization when
10714 * the view hierarchy contains one or several SurfaceView.
10715 * SurfaceView is always considered transparent, but its children are not,
10716 * therefore all View objects remove themselves from the global transparent
10717 * region (passed as a parameter to this function).
10718 *
10719 * @param region The transparent region for this ViewRoot (window).
10720 *
10721 * @return Returns true if the effective visibility of the view at this
10722 * point is opaque, regardless of the transparent region; returns false
10723 * if it is possible for underlying windows to be seen behind the view.
10724 *
10725 * {@hide}
10726 */
10727 public boolean gatherTransparentRegion(Region region) {
10728 final AttachInfo attachInfo = mAttachInfo;
10729 if (region != null && attachInfo != null) {
10730 final int pflags = mPrivateFlags;
10731 if ((pflags & SKIP_DRAW) == 0) {
10732 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10733 // remove it from the transparent region.
10734 final int[] location = attachInfo.mTransparentLocation;
10735 getLocationInWindow(location);
10736 region.op(location[0], location[1], location[0] + mRight - mLeft,
10737 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10738 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10739 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10740 // exists, so we remove the background drawable's non-transparent
10741 // parts from this transparent region.
10742 applyDrawableToTransparentRegion(mBGDrawable, region);
10743 }
10744 }
10745 return true;
10746 }
10747
10748 /**
10749 * Play a sound effect for this view.
10750 *
10751 * <p>The framework will play sound effects for some built in actions, such as
10752 * clicking, but you may wish to play these effects in your widget,
10753 * for instance, for internal navigation.
10754 *
10755 * <p>The sound effect will only be played if sound effects are enabled by the user, and
10756 * {@link #isSoundEffectsEnabled()} is true.
10757 *
10758 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10759 */
10760 public void playSoundEffect(int soundConstant) {
10761 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10762 return;
10763 }
10764 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10765 }
10766
10767 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010768 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010769 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010770 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010771 *
10772 * <p>The framework will provide haptic feedback for some built in actions,
10773 * such as long presses, but you may wish to provide feedback for your
10774 * own widget.
10775 *
10776 * <p>The feedback will only be performed if
10777 * {@link #isHapticFeedbackEnabled()} is true.
10778 *
10779 * @param feedbackConstant One of the constants defined in
10780 * {@link HapticFeedbackConstants}
10781 */
10782 public boolean performHapticFeedback(int feedbackConstant) {
10783 return performHapticFeedback(feedbackConstant, 0);
10784 }
10785
10786 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010787 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -070010788 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -070010789 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010790 *
10791 * @param feedbackConstant One of the constants defined in
10792 * {@link HapticFeedbackConstants}
10793 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10794 */
10795 public boolean performHapticFeedback(int feedbackConstant, int flags) {
10796 if (mAttachInfo == null) {
10797 return false;
10798 }
Romain Guyf607bdc2010-09-10 19:20:06 -070010799 //noinspection SimplifiableIfStatement
Romain Guy812ccbe2010-06-01 14:07:24 -070010800 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010801 && !isHapticFeedbackEnabled()) {
10802 return false;
10803 }
Romain Guy812ccbe2010-06-01 14:07:24 -070010804 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10805 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010806 }
10807
10808 /**
Joe Onorato664644d2011-01-23 17:53:23 -080010809 * Request that the visibility of the status bar be changed.
10810 */
10811 public void setSystemUiVisibility(int visibility) {
10812 if (visibility != mSystemUiVisibility) {
10813 mSystemUiVisibility = visibility;
10814 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10815 mParent.recomputeViewAttributes(this);
10816 }
10817 }
10818 }
10819
10820 /**
10821 * Returns the status bar visibility that this view has requested.
10822 */
Joe Onoratoe595cad2011-01-24 09:22:12 -080010823 public int getSystemUiVisibility() {
Joe Onorato664644d2011-01-23 17:53:23 -080010824 return mSystemUiVisibility;
10825 }
10826
10827 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
10828 mOnSystemUiVisibilityChangeListener = l;
10829 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10830 mParent.recomputeViewAttributes(this);
10831 }
10832 }
10833
10834 /**
10835 */
10836 public void dispatchSystemUiVisibilityChanged(int visibility) {
Joe Onorato14782f72011-01-25 19:53:17 -080010837 mSystemUiVisibility = visibility;
Joe Onorato664644d2011-01-23 17:53:23 -080010838 if (mOnSystemUiVisibilityChangeListener != null) {
10839 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(visibility);
10840 }
10841 }
10842
10843 /**
Joe Malin32736f02011-01-19 16:14:20 -080010844 * Creates an image that the system displays during the drag and drop
10845 * operation. This is called a &quot;drag shadow&quot;. The default implementation
10846 * for a DragShadowBuilder based on a View returns an image that has exactly the same
10847 * appearance as the given View. The default also positions the center of the drag shadow
10848 * directly under the touch point. If no View is provided (the constructor with no parameters
10849 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
10850 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
10851 * default is an invisible drag shadow.
10852 * <p>
10853 * You are not required to use the View you provide to the constructor as the basis of the
10854 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
10855 * anything you want as the drag shadow.
10856 * </p>
10857 * <p>
10858 * You pass a DragShadowBuilder object to the system when you start the drag. The system
10859 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
10860 * size and position of the drag shadow. It uses this data to construct a
10861 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
10862 * so that your application can draw the shadow image in the Canvas.
10863 * </p>
Christopher Tate2c095f32010-10-04 14:13:40 -070010864 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010865 public static class DragShadowBuilder {
Christopher Tatea0374192010-10-05 13:06:41 -070010866 private final WeakReference<View> mView;
Christopher Tate2c095f32010-10-04 14:13:40 -070010867
10868 /**
Joe Malin32736f02011-01-19 16:14:20 -080010869 * Constructs a shadow image builder based on a View. By default, the resulting drag
10870 * shadow will have the same appearance and dimensions as the View, with the touch point
10871 * over the center of the View.
10872 * @param view A View. Any View in scope can be used.
Christopher Tate2c095f32010-10-04 14:13:40 -070010873 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010874 public DragShadowBuilder(View view) {
Christopher Tatea0374192010-10-05 13:06:41 -070010875 mView = new WeakReference<View>(view);
Christopher Tate2c095f32010-10-04 14:13:40 -070010876 }
10877
Christopher Tate17ed60c2011-01-18 12:50:26 -080010878 /**
10879 * Construct a shadow builder object with no associated View. This
10880 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
10881 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
10882 * to supply the drag shadow's dimensions and appearance without
Joe Malin32736f02011-01-19 16:14:20 -080010883 * reference to any View object. If they are not overridden, then the result is an
10884 * invisible drag shadow.
Christopher Tate17ed60c2011-01-18 12:50:26 -080010885 */
10886 public DragShadowBuilder() {
10887 mView = new WeakReference<View>(null);
10888 }
10889
10890 /**
10891 * Returns the View object that had been passed to the
10892 * {@link #View.DragShadowBuilder(View)}
10893 * constructor. If that View parameter was {@code null} or if the
10894 * {@link #View.DragShadowBuilder()}
10895 * constructor was used to instantiate the builder object, this method will return
10896 * null.
10897 *
10898 * @return The View object associate with this builder object.
10899 */
Chris Tate6b391282010-10-14 15:48:59 -070010900 final public View getView() {
10901 return mView.get();
10902 }
10903
Christopher Tate2c095f32010-10-04 14:13:40 -070010904 /**
Joe Malin32736f02011-01-19 16:14:20 -080010905 * Provides the metrics for the shadow image. These include the dimensions of
10906 * the shadow image, and the point within that shadow that should
Christopher Tate2c095f32010-10-04 14:13:40 -070010907 * be centered under the touch location while dragging.
10908 * <p>
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010909 * The default implementation sets the dimensions of the shadow to be the
Joe Malin32736f02011-01-19 16:14:20 -080010910 * same as the dimensions of the View itself and centers the shadow under
10911 * the touch point.
10912 * </p>
Christopher Tate2c095f32010-10-04 14:13:40 -070010913 *
Joe Malin32736f02011-01-19 16:14:20 -080010914 * @param shadowSize A {@link android.graphics.Point} containing the width and height
10915 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
10916 * desired width and must set {@link android.graphics.Point#y} to the desired height of the
10917 * image.
10918 *
10919 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
10920 * shadow image that should be underneath the touch point during the drag and drop
10921 * operation. Your application must set {@link android.graphics.Point#x} to the
10922 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
Christopher Tate2c095f32010-10-04 14:13:40 -070010923 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010924 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
Christopher Tatea0374192010-10-05 13:06:41 -070010925 final View view = mView.get();
10926 if (view != null) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010927 shadowSize.set(view.getWidth(), view.getHeight());
10928 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
Christopher Tatea0374192010-10-05 13:06:41 -070010929 } else {
10930 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10931 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010932 }
10933
10934 /**
Joe Malin32736f02011-01-19 16:14:20 -080010935 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
10936 * based on the dimensions it received from the
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010937 * {@link #onProvideShadowMetrics(Point, Point)} callback.
Christopher Tate2c095f32010-10-04 14:13:40 -070010938 *
Joe Malin32736f02011-01-19 16:14:20 -080010939 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
Christopher Tate2c095f32010-10-04 14:13:40 -070010940 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010941 public void onDrawShadow(Canvas canvas) {
Christopher Tatea0374192010-10-05 13:06:41 -070010942 final View view = mView.get();
10943 if (view != null) {
10944 view.draw(canvas);
10945 } else {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010946 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
Christopher Tatea0374192010-10-05 13:06:41 -070010947 }
Christopher Tate2c095f32010-10-04 14:13:40 -070010948 }
10949 }
10950
10951 /**
Joe Malin32736f02011-01-19 16:14:20 -080010952 * Starts a drag and drop operation. When your application calls this method, it passes a
10953 * {@link android.view.View.DragShadowBuilder} object to the system. The
10954 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
10955 * to get metrics for the drag shadow, and then calls the object's
10956 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
10957 * <p>
10958 * Once the system has the drag shadow, it begins the drag and drop operation by sending
10959 * drag events to all the View objects in your application that are currently visible. It does
10960 * this either by calling the View object's drag listener (an implementation of
10961 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
10962 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
10963 * Both are passed a {@link android.view.DragEvent} object that has a
10964 * {@link android.view.DragEvent#getAction()} value of
10965 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
10966 * </p>
10967 * <p>
10968 * Your application can invoke startDrag() on any attached View object. The View object does not
10969 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
10970 * be related to the View the user selected for dragging.
10971 * </p>
10972 * @param data A {@link android.content.ClipData} object pointing to the data to be
10973 * transferred by the drag and drop operation.
10974 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
10975 * drag shadow.
10976 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
10977 * drop operation. This Object is put into every DragEvent object sent by the system during the
10978 * current drag.
10979 * <p>
10980 * myLocalState is a lightweight mechanism for the sending information from the dragged View
10981 * to the target Views. For example, it can contain flags that differentiate between a
10982 * a copy operation and a move operation.
10983 * </p>
10984 * @param flags Flags that control the drag and drop operation. No flags are currently defined,
10985 * so the parameter should be set to 0.
10986 * @return {@code true} if the method completes successfully, or
10987 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
10988 * do a drag, and so no drag operation is in progress.
Christopher Tatea53146c2010-09-07 11:57:52 -070010989 */
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010990 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010991 Object myLocalState, int flags) {
Christopher Tate2c095f32010-10-04 14:13:40 -070010992 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate02d2b3b2011-01-10 20:43:53 -080010993 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
Christopher Tatea53146c2010-09-07 11:57:52 -070010994 }
10995 boolean okay = false;
10996
Christopher Tate36d4c3f2011-01-07 13:34:24 -080010997 Point shadowSize = new Point();
10998 Point shadowTouchPoint = new Point();
10999 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
Christopher Tate2c095f32010-10-04 14:13:40 -070011000
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011001 if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
11002 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
11003 throw new IllegalStateException("Drag shadow dimensions must not be negative");
Christopher Tate2c095f32010-10-04 14:13:40 -070011004 }
Christopher Tatea53146c2010-09-07 11:57:52 -070011005
Chris Tatea32dcf72010-10-14 12:13:50 -070011006 if (ViewDebug.DEBUG_DRAG) {
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011007 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
11008 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
Chris Tatea32dcf72010-10-14 12:13:50 -070011009 }
Christopher Tatea53146c2010-09-07 11:57:52 -070011010 Surface surface = new Surface();
11011 try {
11012 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
Christopher Tate02d2b3b2011-01-10 20:43:53 -080011013 flags, shadowSize.x, shadowSize.y, surface);
Christopher Tate2c095f32010-10-04 14:13:40 -070011014 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
Christopher Tatea53146c2010-09-07 11:57:52 -070011015 + " surface=" + surface);
11016 if (token != null) {
11017 Canvas canvas = surface.lockCanvas(null);
Romain Guy0bb56672010-10-01 00:25:02 -070011018 try {
Chris Tate6b391282010-10-14 15:48:59 -070011019 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011020 shadowBuilder.onDrawShadow(canvas);
Romain Guy0bb56672010-10-01 00:25:02 -070011021 } finally {
11022 surface.unlockCanvasAndPost(canvas);
11023 }
Christopher Tatea53146c2010-09-07 11:57:52 -070011024
Christopher Tate407b4e92010-11-30 17:14:08 -080011025 final ViewRoot root = getViewRoot();
11026
11027 // Cache the local state object for delivery with DragEvents
11028 root.setLocalDragState(myLocalState);
11029
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011030 // repurpose 'shadowSize' for the last touch point
11031 root.getLastTouchPoint(shadowSize);
Christopher Tate2c095f32010-10-04 14:13:40 -070011032
Christopher Tatea53146c2010-09-07 11:57:52 -070011033 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
Christopher Tate36d4c3f2011-01-07 13:34:24 -080011034 shadowSize.x, shadowSize.y,
11035 shadowTouchPoint.x, shadowTouchPoint.y, data);
Christopher Tate2c095f32010-10-04 14:13:40 -070011036 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
Christopher Tatea53146c2010-09-07 11:57:52 -070011037 }
11038 } catch (Exception e) {
11039 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
11040 surface.destroy();
11041 }
11042
11043 return okay;
11044 }
11045
Christopher Tatea53146c2010-09-07 11:57:52 -070011046 /**
Joe Malin32736f02011-01-19 16:14:20 -080011047 * Handles drag events sent by the system following a call to
11048 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
11049 *<p>
11050 * When the system calls this method, it passes a
11051 * {@link android.view.DragEvent} object. A call to
11052 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
11053 * in DragEvent. The method uses these to determine what is happening in the drag and drop
11054 * operation.
11055 * @param event The {@link android.view.DragEvent} sent by the system.
11056 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
11057 * in DragEvent, indicating the type of drag event represented by this object.
11058 * @return {@code true} if the method was successful, otherwise {@code false}.
11059 * <p>
11060 * The method should return {@code true} in response to an action type of
11061 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
11062 * operation.
11063 * </p>
11064 * <p>
11065 * The method should also return {@code true} in response to an action type of
11066 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
11067 * {@code false} if it didn't.
11068 * </p>
Christopher Tatea53146c2010-09-07 11:57:52 -070011069 */
Christopher Tate5ada6cb2010-10-05 14:15:29 -070011070 public boolean onDragEvent(DragEvent event) {
Christopher Tatea53146c2010-09-07 11:57:52 -070011071 return false;
11072 }
11073
11074 /**
Joe Malin32736f02011-01-19 16:14:20 -080011075 * Detects if this View is enabled and has a drag event listener.
11076 * If both are true, then it calls the drag event listener with the
11077 * {@link android.view.DragEvent} it received. If the drag event listener returns
11078 * {@code true}, then dispatchDragEvent() returns {@code true}.
11079 * <p>
11080 * For all other cases, the method calls the
11081 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
11082 * method and returns its result.
11083 * </p>
11084 * <p>
11085 * This ensures that a drag event is always consumed, even if the View does not have a drag
11086 * event listener. However, if the View has a listener and the listener returns true, then
11087 * onDragEvent() is not called.
11088 * </p>
Christopher Tatea53146c2010-09-07 11:57:52 -070011089 */
11090 public boolean dispatchDragEvent(DragEvent event) {
Chris Tate32affef2010-10-18 15:29:21 -070011091 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
11092 && mOnDragListener.onDrag(this, event)) {
11093 return true;
11094 }
Christopher Tatea53146c2010-09-07 11:57:52 -070011095 return onDragEvent(event);
11096 }
11097
11098 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -070011099 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
11100 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -070011101 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -070011102 */
11103 public void onCloseSystemDialogs(String reason) {
11104 }
Joe Malin32736f02011-01-19 16:14:20 -080011105
Dianne Hackbornffa42482009-09-23 22:20:11 -070011106 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011107 * Given a Drawable whose bounds have been set to draw into this view,
11108 * update a Region being computed for {@link #gatherTransparentRegion} so
11109 * that any non-transparent parts of the Drawable are removed from the
11110 * given transparent region.
11111 *
11112 * @param dr The Drawable whose transparency is to be applied to the region.
11113 * @param region A Region holding the current transparency information,
11114 * where any parts of the region that are set are considered to be
11115 * transparent. On return, this region will be modified to have the
11116 * transparency information reduced by the corresponding parts of the
11117 * Drawable that are not transparent.
11118 * {@hide}
11119 */
11120 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
11121 if (DBG) {
11122 Log.i("View", "Getting transparent region for: " + this);
11123 }
11124 final Region r = dr.getTransparentRegion();
11125 final Rect db = dr.getBounds();
11126 final AttachInfo attachInfo = mAttachInfo;
11127 if (r != null && attachInfo != null) {
11128 final int w = getRight()-getLeft();
11129 final int h = getBottom()-getTop();
11130 if (db.left > 0) {
11131 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
11132 r.op(0, 0, db.left, h, Region.Op.UNION);
11133 }
11134 if (db.right < w) {
11135 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
11136 r.op(db.right, 0, w, h, Region.Op.UNION);
11137 }
11138 if (db.top > 0) {
11139 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
11140 r.op(0, 0, w, db.top, Region.Op.UNION);
11141 }
11142 if (db.bottom < h) {
11143 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
11144 r.op(0, db.bottom, w, h, Region.Op.UNION);
11145 }
11146 final int[] location = attachInfo.mTransparentLocation;
11147 getLocationInWindow(location);
11148 r.translate(location[0], location[1]);
11149 region.op(r, Region.Op.INTERSECT);
11150 } else {
11151 region.op(db, Region.Op.DIFFERENCE);
11152 }
11153 }
11154
Adam Powelle14579b2009-12-16 18:39:52 -080011155 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011156 mHasPerformedLongPress = false;
11157
11158 if (mPendingCheckForLongPress == null) {
11159 mPendingCheckForLongPress = new CheckForLongPress();
11160 }
11161 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -080011162 postDelayed(mPendingCheckForLongPress,
11163 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011164 }
11165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011166 /**
11167 * Inflate a view from an XML resource. This convenience method wraps the {@link
11168 * LayoutInflater} class, which provides a full range of options for view inflation.
11169 *
11170 * @param context The Context object for your activity or application.
11171 * @param resource The resource ID to inflate
11172 * @param root A view group that will be the parent. Used to properly inflate the
11173 * layout_* parameters.
11174 * @see LayoutInflater
11175 */
11176 public static View inflate(Context context, int resource, ViewGroup root) {
11177 LayoutInflater factory = LayoutInflater.from(context);
11178 return factory.inflate(resource, root);
11179 }
Romain Guy33e72ae2010-07-17 12:40:29 -070011180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011181 /**
Adam Powell637d3372010-08-25 14:37:03 -070011182 * Scroll the view with standard behavior for scrolling beyond the normal
11183 * content boundaries. Views that call this method should override
11184 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
11185 * results of an over-scroll operation.
11186 *
11187 * Views can use this method to handle any touch or fling-based scrolling.
11188 *
11189 * @param deltaX Change in X in pixels
11190 * @param deltaY Change in Y in pixels
11191 * @param scrollX Current X scroll value in pixels before applying deltaX
11192 * @param scrollY Current Y scroll value in pixels before applying deltaY
11193 * @param scrollRangeX Maximum content scroll range along the X axis
11194 * @param scrollRangeY Maximum content scroll range along the Y axis
11195 * @param maxOverScrollX Number of pixels to overscroll by in either direction
11196 * along the X axis.
11197 * @param maxOverScrollY Number of pixels to overscroll by in either direction
11198 * along the Y axis.
11199 * @param isTouchEvent true if this scroll operation is the result of a touch event.
11200 * @return true if scrolling was clamped to an over-scroll boundary along either
11201 * axis, false otherwise.
11202 */
11203 protected boolean overScrollBy(int deltaX, int deltaY,
11204 int scrollX, int scrollY,
11205 int scrollRangeX, int scrollRangeY,
11206 int maxOverScrollX, int maxOverScrollY,
11207 boolean isTouchEvent) {
11208 final int overScrollMode = mOverScrollMode;
11209 final boolean canScrollHorizontal =
11210 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
11211 final boolean canScrollVertical =
11212 computeVerticalScrollRange() > computeVerticalScrollExtent();
11213 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
11214 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
11215 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
11216 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
11217
11218 int newScrollX = scrollX + deltaX;
11219 if (!overScrollHorizontal) {
11220 maxOverScrollX = 0;
11221 }
11222
11223 int newScrollY = scrollY + deltaY;
11224 if (!overScrollVertical) {
11225 maxOverScrollY = 0;
11226 }
11227
11228 // Clamp values if at the limits and record
11229 final int left = -maxOverScrollX;
11230 final int right = maxOverScrollX + scrollRangeX;
11231 final int top = -maxOverScrollY;
11232 final int bottom = maxOverScrollY + scrollRangeY;
11233
11234 boolean clampedX = false;
11235 if (newScrollX > right) {
11236 newScrollX = right;
11237 clampedX = true;
11238 } else if (newScrollX < left) {
11239 newScrollX = left;
11240 clampedX = true;
11241 }
11242
11243 boolean clampedY = false;
11244 if (newScrollY > bottom) {
11245 newScrollY = bottom;
11246 clampedY = true;
11247 } else if (newScrollY < top) {
11248 newScrollY = top;
11249 clampedY = true;
11250 }
11251
11252 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
11253
11254 return clampedX || clampedY;
11255 }
11256
11257 /**
11258 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
11259 * respond to the results of an over-scroll operation.
11260 *
11261 * @param scrollX New X scroll value in pixels
11262 * @param scrollY New Y scroll value in pixels
11263 * @param clampedX True if scrollX was clamped to an over-scroll boundary
11264 * @param clampedY True if scrollY was clamped to an over-scroll boundary
11265 */
11266 protected void onOverScrolled(int scrollX, int scrollY,
11267 boolean clampedX, boolean clampedY) {
11268 // Intentionally empty.
11269 }
11270
11271 /**
11272 * Returns the over-scroll mode for this view. The result will be
11273 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
11274 * (allow over-scrolling only if the view content is larger than the container),
11275 * or {@link #OVER_SCROLL_NEVER}.
11276 *
11277 * @return This view's over-scroll mode.
11278 */
11279 public int getOverScrollMode() {
11280 return mOverScrollMode;
11281 }
11282
11283 /**
11284 * Set the over-scroll mode for this view. Valid over-scroll modes are
11285 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
11286 * (allow over-scrolling only if the view content is larger than the container),
11287 * or {@link #OVER_SCROLL_NEVER}.
11288 *
11289 * Setting the over-scroll mode of a view will have an effect only if the
11290 * view is capable of scrolling.
11291 *
11292 * @param overScrollMode The new over-scroll mode for this view.
11293 */
11294 public void setOverScrollMode(int overScrollMode) {
11295 if (overScrollMode != OVER_SCROLL_ALWAYS &&
11296 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
11297 overScrollMode != OVER_SCROLL_NEVER) {
11298 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
11299 }
11300 mOverScrollMode = overScrollMode;
11301 }
11302
11303 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011304 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
11305 * Each MeasureSpec represents a requirement for either the width or the height.
11306 * A MeasureSpec is comprised of a size and a mode. There are three possible
11307 * modes:
11308 * <dl>
11309 * <dt>UNSPECIFIED</dt>
11310 * <dd>
11311 * The parent has not imposed any constraint on the child. It can be whatever size
11312 * it wants.
11313 * </dd>
11314 *
11315 * <dt>EXACTLY</dt>
11316 * <dd>
11317 * The parent has determined an exact size for the child. The child is going to be
11318 * given those bounds regardless of how big it wants to be.
11319 * </dd>
11320 *
11321 * <dt>AT_MOST</dt>
11322 * <dd>
11323 * The child can be as large as it wants up to the specified size.
11324 * </dd>
11325 * </dl>
11326 *
11327 * MeasureSpecs are implemented as ints to reduce object allocation. This class
11328 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
11329 */
11330 public static class MeasureSpec {
11331 private static final int MODE_SHIFT = 30;
11332 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
11333
11334 /**
11335 * Measure specification mode: The parent has not imposed any constraint
11336 * on the child. It can be whatever size it wants.
11337 */
11338 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
11339
11340 /**
11341 * Measure specification mode: The parent has determined an exact size
11342 * for the child. The child is going to be given those bounds regardless
11343 * of how big it wants to be.
11344 */
11345 public static final int EXACTLY = 1 << MODE_SHIFT;
11346
11347 /**
11348 * Measure specification mode: The child can be as large as it wants up
11349 * to the specified size.
11350 */
11351 public static final int AT_MOST = 2 << MODE_SHIFT;
11352
11353 /**
11354 * Creates a measure specification based on the supplied size and mode.
11355 *
11356 * The mode must always be one of the following:
11357 * <ul>
11358 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
11359 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
11360 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
11361 * </ul>
11362 *
11363 * @param size the size of the measure specification
11364 * @param mode the mode of the measure specification
11365 * @return the measure specification based on size and mode
11366 */
11367 public static int makeMeasureSpec(int size, int mode) {
11368 return size + mode;
11369 }
11370
11371 /**
11372 * Extracts the mode from the supplied measure specification.
11373 *
11374 * @param measureSpec the measure specification to extract the mode from
11375 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
11376 * {@link android.view.View.MeasureSpec#AT_MOST} or
11377 * {@link android.view.View.MeasureSpec#EXACTLY}
11378 */
11379 public static int getMode(int measureSpec) {
11380 return (measureSpec & MODE_MASK);
11381 }
11382
11383 /**
11384 * Extracts the size from the supplied measure specification.
11385 *
11386 * @param measureSpec the measure specification to extract the size from
11387 * @return the size in pixels defined in the supplied measure specification
11388 */
11389 public static int getSize(int measureSpec) {
11390 return (measureSpec & ~MODE_MASK);
11391 }
11392
11393 /**
11394 * Returns a String representation of the specified measure
11395 * specification.
11396 *
11397 * @param measureSpec the measure specification to convert to a String
11398 * @return a String with the following format: "MeasureSpec: MODE SIZE"
11399 */
11400 public static String toString(int measureSpec) {
11401 int mode = getMode(measureSpec);
11402 int size = getSize(measureSpec);
11403
11404 StringBuilder sb = new StringBuilder("MeasureSpec: ");
11405
11406 if (mode == UNSPECIFIED)
11407 sb.append("UNSPECIFIED ");
11408 else if (mode == EXACTLY)
11409 sb.append("EXACTLY ");
11410 else if (mode == AT_MOST)
11411 sb.append("AT_MOST ");
11412 else
11413 sb.append(mode).append(" ");
11414
11415 sb.append(size);
11416 return sb.toString();
11417 }
11418 }
11419
11420 class CheckForLongPress implements Runnable {
11421
11422 private int mOriginalWindowAttachCount;
11423
11424 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011425 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011426 && mOriginalWindowAttachCount == mWindowAttachCount) {
11427 if (performLongClick()) {
11428 mHasPerformedLongPress = true;
11429 }
11430 }
11431 }
11432
11433 public void rememberWindowAttachCount() {
11434 mOriginalWindowAttachCount = mWindowAttachCount;
11435 }
11436 }
Joe Malin32736f02011-01-19 16:14:20 -080011437
Adam Powelle14579b2009-12-16 18:39:52 -080011438 private final class CheckForTap implements Runnable {
11439 public void run() {
11440 mPrivateFlags &= ~PREPRESSED;
11441 mPrivateFlags |= PRESSED;
11442 refreshDrawableState();
11443 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
11444 postCheckForLongClick(ViewConfiguration.getTapTimeout());
11445 }
11446 }
11447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011448
Adam Powella35d7682010-03-12 14:48:13 -080011449 private final class PerformClick implements Runnable {
11450 public void run() {
11451 performClick();
11452 }
11453 }
11454
Dianne Hackborn63042d62011-01-26 18:56:29 -080011455 /** @hide */
11456 public void hackTurnOffWindowResizeAnim(boolean off) {
11457 mAttachInfo.mTurnOffWindowResizeAnim = off;
11458 }
Joe Malin32736f02011-01-19 16:14:20 -080011459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011460 /**
11461 * Interface definition for a callback to be invoked when a key event is
11462 * dispatched to this view. The callback will be invoked before the key
11463 * event is given to the view.
11464 */
11465 public interface OnKeyListener {
11466 /**
11467 * Called when a key is dispatched to a view. This allows listeners to
11468 * get a chance to respond before the target view.
11469 *
11470 * @param v The view the key has been dispatched to.
11471 * @param keyCode The code for the physical key that was pressed
11472 * @param event The KeyEvent object containing full information about
11473 * the event.
11474 * @return True if the listener has consumed the event, false otherwise.
11475 */
11476 boolean onKey(View v, int keyCode, KeyEvent event);
11477 }
11478
11479 /**
11480 * Interface definition for a callback to be invoked when a touch event is
11481 * dispatched to this view. The callback will be invoked before the touch
11482 * event is given to the view.
11483 */
11484 public interface OnTouchListener {
11485 /**
11486 * Called when a touch event is dispatched to a view. This allows listeners to
11487 * get a chance to respond before the target view.
11488 *
11489 * @param v The view the touch event has been dispatched to.
11490 * @param event The MotionEvent object containing full information about
11491 * the event.
11492 * @return True if the listener has consumed the event, false otherwise.
11493 */
11494 boolean onTouch(View v, MotionEvent event);
11495 }
11496
11497 /**
11498 * Interface definition for a callback to be invoked when a view has been clicked and held.
11499 */
11500 public interface OnLongClickListener {
11501 /**
11502 * Called when a view has been clicked and held.
11503 *
11504 * @param v The view that was clicked and held.
11505 *
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -080011506 * @return true if the callback consumed the long click, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011507 */
11508 boolean onLongClick(View v);
11509 }
11510
11511 /**
Chris Tate32affef2010-10-18 15:29:21 -070011512 * Interface definition for a callback to be invoked when a drag is being dispatched
11513 * to this view. The callback will be invoked before the hosting view's own
11514 * onDrag(event) method. If the listener wants to fall back to the hosting view's
11515 * onDrag(event) behavior, it should return 'false' from this callback.
11516 */
11517 public interface OnDragListener {
11518 /**
11519 * Called when a drag event is dispatched to a view. This allows listeners
11520 * to get a chance to override base View behavior.
11521 *
Joe Malin32736f02011-01-19 16:14:20 -080011522 * @param v The View that received the drag event.
11523 * @param event The {@link android.view.DragEvent} object for the drag event.
11524 * @return {@code true} if the drag event was handled successfully, or {@code false}
11525 * if the drag event was not handled. Note that {@code false} will trigger the View
11526 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
Chris Tate32affef2010-10-18 15:29:21 -070011527 */
11528 boolean onDrag(View v, DragEvent event);
11529 }
11530
11531 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011532 * Interface definition for a callback to be invoked when the focus state of
11533 * a view changed.
11534 */
11535 public interface OnFocusChangeListener {
11536 /**
11537 * Called when the focus state of a view has changed.
11538 *
11539 * @param v The view whose state has changed.
11540 * @param hasFocus The new focus state of v.
11541 */
11542 void onFocusChange(View v, boolean hasFocus);
11543 }
11544
11545 /**
11546 * Interface definition for a callback to be invoked when a view is clicked.
11547 */
11548 public interface OnClickListener {
11549 /**
11550 * Called when a view has been clicked.
11551 *
11552 * @param v The view that was clicked.
11553 */
11554 void onClick(View v);
11555 }
11556
11557 /**
11558 * Interface definition for a callback to be invoked when the context menu
11559 * for this view is being built.
11560 */
11561 public interface OnCreateContextMenuListener {
11562 /**
11563 * Called when the context menu for this view is being built. It is not
11564 * safe to hold onto the menu after this method returns.
11565 *
11566 * @param menu The context menu that is being built
11567 * @param v The view for which the context menu is being built
11568 * @param menuInfo Extra information about the item for which the
11569 * context menu should be shown. This information will vary
11570 * depending on the class of v.
11571 */
11572 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
11573 }
11574
Joe Onorato664644d2011-01-23 17:53:23 -080011575 /**
11576 * Interface definition for a callback to be invoked when the status bar changes
11577 * visibility.
11578 *
11579 * @see #setOnSystemUiVisibilityChangeListener
11580 */
11581 public interface OnSystemUiVisibilityChangeListener {
11582 /**
11583 * Called when the status bar changes visibility because of a call to
11584 * {@link #setSystemUiVisibility}.
11585 *
11586 * @param visibility {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}.
11587 */
11588 public void onSystemUiVisibilityChange(int visibility);
11589 }
11590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011591 private final class UnsetPressedState implements Runnable {
11592 public void run() {
11593 setPressed(false);
11594 }
11595 }
11596
11597 /**
11598 * Base class for derived classes that want to save and restore their own
11599 * state in {@link android.view.View#onSaveInstanceState()}.
11600 */
11601 public static class BaseSavedState extends AbsSavedState {
11602 /**
11603 * Constructor used when reading from a parcel. Reads the state of the superclass.
11604 *
11605 * @param source
11606 */
11607 public BaseSavedState(Parcel source) {
11608 super(source);
11609 }
11610
11611 /**
11612 * Constructor called by derived classes when creating their SavedState objects
11613 *
11614 * @param superState The state of the superclass of this view
11615 */
11616 public BaseSavedState(Parcelable superState) {
11617 super(superState);
11618 }
11619
11620 public static final Parcelable.Creator<BaseSavedState> CREATOR =
11621 new Parcelable.Creator<BaseSavedState>() {
11622 public BaseSavedState createFromParcel(Parcel in) {
11623 return new BaseSavedState(in);
11624 }
11625
11626 public BaseSavedState[] newArray(int size) {
11627 return new BaseSavedState[size];
11628 }
11629 };
11630 }
11631
11632 /**
11633 * A set of information given to a view when it is attached to its parent
11634 * window.
11635 */
11636 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011637 interface Callbacks {
11638 void playSoundEffect(int effectId);
11639 boolean performHapticFeedback(int effectId, boolean always);
11640 }
11641
11642 /**
11643 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
11644 * to a Handler. This class contains the target (View) to invalidate and
11645 * the coordinates of the dirty rectangle.
11646 *
11647 * For performance purposes, this class also implements a pool of up to
11648 * POOL_LIMIT objects that get reused. This reduces memory allocations
11649 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011650 */
Romain Guyd928d682009-03-31 17:52:16 -070011651 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011652 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070011653 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
11654 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070011655 public InvalidateInfo newInstance() {
11656 return new InvalidateInfo();
11657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011658
Romain Guyd928d682009-03-31 17:52:16 -070011659 public void onAcquired(InvalidateInfo element) {
11660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011661
Romain Guyd928d682009-03-31 17:52:16 -070011662 public void onReleased(InvalidateInfo element) {
11663 }
11664 }, POOL_LIMIT)
11665 );
11666
11667 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011668
11669 View target;
11670
11671 int left;
11672 int top;
11673 int right;
11674 int bottom;
11675
Romain Guyd928d682009-03-31 17:52:16 -070011676 public void setNextPoolable(InvalidateInfo element) {
11677 mNext = element;
11678 }
11679
11680 public InvalidateInfo getNextPoolable() {
11681 return mNext;
11682 }
11683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011684 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070011685 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011686 }
11687
11688 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070011689 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011690 }
11691 }
11692
11693 final IWindowSession mSession;
11694
11695 final IWindow mWindow;
11696
11697 final IBinder mWindowToken;
11698
11699 final Callbacks mRootCallbacks;
11700
Chet Haasedaf98e92011-01-10 14:10:36 -080011701 Canvas mHardwareCanvas;
11702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011703 /**
11704 * The top view of the hierarchy.
11705 */
11706 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070011707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011708 IBinder mPanelParentWindowToken;
11709 Surface mSurface;
11710
Romain Guyb051e892010-09-28 19:09:36 -070011711 boolean mHardwareAccelerated;
Dianne Hackborn7eec10e2010-11-12 18:03:47 -080011712 boolean mHardwareAccelerationRequested;
Romain Guyb051e892010-09-28 19:09:36 -070011713 HardwareRenderer mHardwareRenderer;
Joe Malin32736f02011-01-19 16:14:20 -080011714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011715 /**
Romain Guy8506ab42009-06-11 17:35:47 -070011716 * Scale factor used by the compatibility mode
11717 */
11718 float mApplicationScale;
11719
11720 /**
11721 * Indicates whether the application is in compatibility mode
11722 */
11723 boolean mScalingRequired;
11724
11725 /**
Dianne Hackborn63042d62011-01-26 18:56:29 -080011726 * If set, ViewRoot doesn't use its lame animation for when the window resizes.
11727 */
11728 boolean mTurnOffWindowResizeAnim;
Joe Malin32736f02011-01-19 16:14:20 -080011729
Dianne Hackborn63042d62011-01-26 18:56:29 -080011730 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011731 * Left position of this view's window
11732 */
11733 int mWindowLeft;
11734
11735 /**
11736 * Top position of this view's window
11737 */
11738 int mWindowTop;
11739
11740 /**
Adam Powell26153a32010-11-08 15:22:27 -080011741 * Indicates whether views need to use 32-bit drawing caches
Romain Guy35b38ce2009-10-07 13:38:55 -070011742 */
Adam Powell26153a32010-11-08 15:22:27 -080011743 boolean mUse32BitDrawingCache;
Romain Guy35b38ce2009-10-07 13:38:55 -070011744
11745 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011746 * For windows that are full-screen but using insets to layout inside
11747 * of the screen decorations, these are the current insets for the
11748 * content of the window.
11749 */
11750 final Rect mContentInsets = new Rect();
11751
11752 /**
11753 * For windows that are full-screen but using insets to layout inside
11754 * of the screen decorations, these are the current insets for the
11755 * actual visible parts of the window.
11756 */
11757 final Rect mVisibleInsets = new Rect();
11758
11759 /**
11760 * The internal insets given by this window. This value is
11761 * supplied by the client (through
11762 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
11763 * be given to the window manager when changed to be used in laying
11764 * out windows behind it.
11765 */
11766 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
11767 = new ViewTreeObserver.InternalInsetsInfo();
11768
11769 /**
11770 * All views in the window's hierarchy that serve as scroll containers,
11771 * used to determine if the window can be resized or must be panned
11772 * to adjust for a soft input area.
11773 */
11774 final ArrayList<View> mScrollContainers = new ArrayList<View>();
11775
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070011776 final KeyEvent.DispatcherState mKeyDispatchState
11777 = new KeyEvent.DispatcherState();
11778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011779 /**
11780 * Indicates whether the view's window currently has the focus.
11781 */
11782 boolean mHasWindowFocus;
11783
11784 /**
11785 * The current visibility of the window.
11786 */
11787 int mWindowVisibility;
11788
11789 /**
11790 * Indicates the time at which drawing started to occur.
11791 */
11792 long mDrawingTime;
11793
11794 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070011795 * Indicates whether or not ignoring the DIRTY_MASK flags.
11796 */
11797 boolean mIgnoreDirtyState;
11798
11799 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011800 * Indicates whether the view's window is currently in touch mode.
11801 */
11802 boolean mInTouchMode;
11803
11804 /**
11805 * Indicates that ViewRoot should trigger a global layout change
11806 * the next time it performs a traversal
11807 */
11808 boolean mRecomputeGlobalAttributes;
11809
11810 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011811 * Set during a traveral if any views want to keep the screen on.
11812 */
11813 boolean mKeepScreenOn;
11814
11815 /**
Joe Onorato664644d2011-01-23 17:53:23 -080011816 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
11817 */
11818 int mSystemUiVisibility;
11819
11820 /**
11821 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
11822 * attached.
11823 */
11824 boolean mHasSystemUiListeners;
11825
11826 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011827 * Set if the visibility of any views has changed.
11828 */
11829 boolean mViewVisibilityChanged;
11830
11831 /**
11832 * Set to true if a view has been scrolled.
11833 */
11834 boolean mViewScrollChanged;
11835
11836 /**
11837 * Global to the view hierarchy used as a temporary for dealing with
11838 * x/y points in the transparent region computations.
11839 */
11840 final int[] mTransparentLocation = new int[2];
11841
11842 /**
11843 * Global to the view hierarchy used as a temporary for dealing with
11844 * x/y points in the ViewGroup.invalidateChild implementation.
11845 */
11846 final int[] mInvalidateChildLocation = new int[2];
11847
Chet Haasec3aa3612010-06-17 08:50:37 -070011848
11849 /**
11850 * Global to the view hierarchy used as a temporary for dealing with
11851 * x/y location when view is transformed.
11852 */
11853 final float[] mTmpTransformLocation = new float[2];
11854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011855 /**
11856 * The view tree observer used to dispatch global events like
11857 * layout, pre-draw, touch mode change, etc.
11858 */
11859 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11860
11861 /**
11862 * A Canvas used by the view hierarchy to perform bitmap caching.
11863 */
11864 Canvas mCanvas;
11865
11866 /**
11867 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11868 * handler can be used to pump events in the UI events queue.
11869 */
11870 final Handler mHandler;
11871
11872 /**
11873 * Identifier for messages requesting the view to be invalidated.
11874 * Such messages should be sent to {@link #mHandler}.
11875 */
11876 static final int INVALIDATE_MSG = 0x1;
11877
11878 /**
11879 * Identifier for messages requesting the view to invalidate a region.
11880 * Such messages should be sent to {@link #mHandler}.
11881 */
11882 static final int INVALIDATE_RECT_MSG = 0x2;
11883
11884 /**
11885 * Temporary for use in computing invalidate rectangles while
11886 * calling up the hierarchy.
11887 */
11888 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070011889
11890 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070011891 * Temporary for use in computing hit areas with transformed views
11892 */
11893 final RectF mTmpTransformRect = new RectF();
11894
11895 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070011896 * Temporary list for use in collecting focusable descendents of a view.
11897 */
11898 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
11899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011900 /**
11901 * Creates a new set of attachment information with the specified
11902 * events handler and thread.
11903 *
11904 * @param handler the events handler the view must use
11905 */
11906 AttachInfo(IWindowSession session, IWindow window,
11907 Handler handler, Callbacks effectPlayer) {
11908 mSession = session;
11909 mWindow = window;
11910 mWindowToken = window.asBinder();
11911 mHandler = handler;
11912 mRootCallbacks = effectPlayer;
11913 }
11914 }
11915
11916 /**
11917 * <p>ScrollabilityCache holds various fields used by a View when scrolling
11918 * is supported. This avoids keeping too many unused fields in most
11919 * instances of View.</p>
11920 */
Mike Cleronf116bf82009-09-27 19:14:12 -070011921 private static class ScrollabilityCache implements Runnable {
Joe Malin32736f02011-01-19 16:14:20 -080011922
Mike Cleronf116bf82009-09-27 19:14:12 -070011923 /**
11924 * Scrollbars are not visible
11925 */
11926 public static final int OFF = 0;
11927
11928 /**
11929 * Scrollbars are visible
11930 */
11931 public static final int ON = 1;
11932
11933 /**
11934 * Scrollbars are fading away
11935 */
11936 public static final int FADING = 2;
11937
11938 public boolean fadeScrollBars;
Joe Malin32736f02011-01-19 16:14:20 -080011939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011940 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070011941 public int scrollBarDefaultDelayBeforeFade;
11942 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011943
11944 public int scrollBarSize;
11945 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070011946 public float[] interpolatorValues;
11947 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011948
11949 public final Paint paint;
11950 public final Matrix matrix;
11951 public Shader shader;
11952
Mike Cleronf116bf82009-09-27 19:14:12 -070011953 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
11954
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080011955 private static final float[] OPAQUE = { 255 };
11956 private static final float[] TRANSPARENT = { 0.0f };
Joe Malin32736f02011-01-19 16:14:20 -080011957
Mike Cleronf116bf82009-09-27 19:14:12 -070011958 /**
11959 * When fading should start. This time moves into the future every time
11960 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11961 */
11962 public long fadeStartTime;
11963
11964
11965 /**
11966 * The current state of the scrollbars: ON, OFF, or FADING
11967 */
11968 public int state = OFF;
11969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011970 private int mLastColor;
11971
Mike Cleronf116bf82009-09-27 19:14:12 -070011972 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011973 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11974 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070011975 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11976 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011977
11978 paint = new Paint();
11979 matrix = new Matrix();
11980 // use use a height of 1, and then wack the matrix each time we
11981 // actually use it.
11982 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984 paint.setShader(shader);
11985 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070011986 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011987 }
Romain Guy8506ab42009-06-11 17:35:47 -070011988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011989 public void setFadeColor(int color) {
11990 if (color != 0 && color != mLastColor) {
11991 mLastColor = color;
11992 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070011993
Romain Guye55e1a72009-08-27 10:42:26 -070011994 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
11995 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070011996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011997 paint.setShader(shader);
11998 // Restore the default transfer mode (src_over)
11999 paint.setXfermode(null);
12000 }
12001 }
Joe Malin32736f02011-01-19 16:14:20 -080012002
Mike Cleronf116bf82009-09-27 19:14:12 -070012003 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070012004 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070012005 if (now >= fadeStartTime) {
12006
12007 // the animation fades the scrollbars out by changing
12008 // the opacity (alpha) from fully opaque to fully
12009 // transparent
12010 int nextFrame = (int) now;
12011 int framesCount = 0;
12012
12013 Interpolator interpolator = scrollBarInterpolator;
12014
12015 // Start opaque
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080012016 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
Mike Cleronf116bf82009-09-27 19:14:12 -070012017
12018 // End transparent
12019 nextFrame += scrollBarFadeDuration;
Gilles Debunne3dbf55c2010-12-16 10:31:51 -080012020 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
Mike Cleronf116bf82009-09-27 19:14:12 -070012021
12022 state = FADING;
12023
12024 // Kick off the fade animation
Romain Guy0fd89bf2011-01-26 15:41:30 -080012025 host.invalidate(true);
Mike Cleronf116bf82009-09-27 19:14:12 -070012026 }
12027 }
12028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012029 }
12030}