blob: 833fa709e55861e03d1563c48fa028c5d5eef50f [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
svetoslavganov75986cf2009-05-14 22:28:01 -070019import com.android.internal.R;
20import com.android.internal.view.menu.MenuBuilder;
21
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080023import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.res.Resources;
25import android.content.res.TypedArray;
26import android.graphics.Bitmap;
Adam Powell2b342f02010-08-18 18:14:13 -070027import android.graphics.Camera;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.graphics.Canvas;
Mike Cleronf116bf82009-09-27 19:14:12 -070029import android.graphics.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.graphics.LinearGradient;
31import android.graphics.Matrix;
32import android.graphics.Paint;
33import android.graphics.PixelFormat;
svetoslavganov75986cf2009-05-14 22:28:01 -070034import android.graphics.Point;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.graphics.PorterDuff;
36import android.graphics.PorterDuffXfermode;
37import android.graphics.Rect;
Adam Powell6e346362010-07-23 10:18:23 -070038import android.graphics.RectF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.graphics.Region;
40import android.graphics.Shader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.graphics.drawable.ColorDrawable;
42import android.graphics.drawable.Drawable;
43import android.os.Handler;
44import android.os.IBinder;
45import android.os.Message;
46import android.os.Parcel;
47import android.os.Parcelable;
48import android.os.RemoteException;
49import android.os.SystemClock;
50import android.os.SystemProperties;
51import android.util.AttributeSet;
svetoslavganov75986cf2009-05-14 22:28:01 -070052import android.util.Config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.util.EventLog;
54import android.util.Log;
Romain Guyd928d682009-03-31 17:52:16 -070055import android.util.Pool;
svetoslavganov75986cf2009-05-14 22:28:01 -070056import android.util.Poolable;
Romain Guyd928d682009-03-31 17:52:16 -070057import android.util.PoolableManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070058import android.util.Pools;
59import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.ContextMenu.ContextMenuInfo;
svetoslavganov75986cf2009-05-14 22:28:01 -070061import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.animation.Animation;
Mike Cleron3ecd58c2009-09-28 11:39:02 -070065import android.view.animation.AnimationUtils;
svetoslavganov75986cf2009-05-14 22:28:01 -070066import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.view.inputmethod.InputConnection;
68import android.view.inputmethod.InputMethodManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.widget.ScrollBarDrawable;
70
svetoslavganov75986cf2009-05-14 22:28:01 -070071import java.lang.reflect.InvocationTargetException;
72import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.util.ArrayList;
74import java.util.Arrays;
Chet Haase21cd1382010-09-01 17:42:29 -070075import java.util.List;
Romain Guyd90a3312009-05-06 14:54:28 -070076import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077
78/**
79 * <p>
80 * This class represents the basic building block for user interface components. A View
81 * occupies a rectangular area on the screen and is responsible for drawing and
82 * event handling. View is the base class for <em>widgets</em>, which are
Romain Guy8506ab42009-06-11 17:35:47 -070083 * used to create interactive UI components (buttons, text fields, etc.). The
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
85 * are invisible containers that hold other Views (or other ViewGroups) and define
86 * their layout properties.
87 * </p>
88 *
89 * <div class="special">
Romain Guy8506ab42009-06-11 17:35:47 -070090 * <p>For an introduction to using this class to develop your
91 * application's user interface, read the Developer Guide documentation on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
Romain Guy8506ab42009-06-11 17:35:47 -070093 * include:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
95 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
96 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
102 * </p>
103 * </div>
Romain Guy8506ab42009-06-11 17:35:47 -0700104 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 * <a name="Using"></a>
106 * <h3>Using Views</h3>
107 * <p>
108 * All of the views in a window are arranged in a single tree. You can add views
109 * either from code or by specifying a tree of views in one or more XML layout
110 * files. There are many specialized subclasses of views that act as controls or
111 * are capable of displaying text, images, or other content.
112 * </p>
113 * <p>
114 * Once you have created a tree of views, there are typically a few types of
115 * common operations you may wish to perform:
116 * <ul>
117 * <li><strong>Set properties:</strong> for example setting the text of a
118 * {@link android.widget.TextView}. The available properties and the methods
119 * that set them will vary among the different subclasses of views. Note that
120 * properties that are known at build time can be set in the XML layout
121 * files.</li>
122 * <li><strong>Set focus:</strong> The framework will handled moving focus in
123 * response to user input. To force focus to a specific view, call
124 * {@link #requestFocus}.</li>
125 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
126 * that will be notified when something interesting happens to the view. For
127 * example, all views will let you set a listener to be notified when the view
128 * gains or loses focus. You can register such a listener using
129 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
130 * specialized listeners. For example, a Button exposes a listener to notify
131 * clients when the button is clicked.</li>
132 * <li><strong>Set visibility:</strong> You can hide or show views using
133 * {@link #setVisibility}.</li>
134 * </ul>
135 * </p>
136 * <p><em>
137 * Note: The Android framework is responsible for measuring, laying out and
138 * drawing views. You should not call methods that perform these actions on
139 * views yourself unless you are actually implementing a
140 * {@link android.view.ViewGroup}.
141 * </em></p>
142 *
143 * <a name="Lifecycle"></a>
144 * <h3>Implementing a Custom View</h3>
145 *
146 * <p>
147 * To implement a custom view, you will usually begin by providing overrides for
148 * some of the standard methods that the framework calls on all views. You do
149 * not need to override all of these methods. In fact, you can start by just
150 * overriding {@link #onDraw(android.graphics.Canvas)}.
151 * <table border="2" width="85%" align="center" cellpadding="5">
152 * <thead>
153 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
154 * </thead>
155 *
156 * <tbody>
157 * <tr>
158 * <td rowspan="2">Creation</td>
159 * <td>Constructors</td>
160 * <td>There is a form of the constructor that are called when the view
161 * is created from code and a form that is called when the view is
162 * inflated from a layout file. The second form should parse and apply
163 * any attributes defined in the layout file.
164 * </td>
165 * </tr>
166 * <tr>
167 * <td><code>{@link #onFinishInflate()}</code></td>
168 * <td>Called after a view and all of its children has been inflated
169 * from XML.</td>
170 * </tr>
171 *
172 * <tr>
173 * <td rowspan="3">Layout</td>
174 * <td><code>{@link #onMeasure}</code></td>
175 * <td>Called to determine the size requirements for this view and all
176 * of its children.
177 * </td>
178 * </tr>
179 * <tr>
180 * <td><code>{@link #onLayout}</code></td>
181 * <td>Called when this view should assign a size and position to all
182 * of its children.
183 * </td>
184 * </tr>
185 * <tr>
186 * <td><code>{@link #onSizeChanged}</code></td>
187 * <td>Called when the size of this view has changed.
188 * </td>
189 * </tr>
190 *
191 * <tr>
192 * <td>Drawing</td>
193 * <td><code>{@link #onDraw}</code></td>
194 * <td>Called when the view should render its content.
195 * </td>
196 * </tr>
197 *
198 * <tr>
199 * <td rowspan="4">Event processing</td>
200 * <td><code>{@link #onKeyDown}</code></td>
201 * <td>Called when a new key event occurs.
202 * </td>
203 * </tr>
204 * <tr>
205 * <td><code>{@link #onKeyUp}</code></td>
206 * <td>Called when a key up event occurs.
207 * </td>
208 * </tr>
209 * <tr>
210 * <td><code>{@link #onTrackballEvent}</code></td>
211 * <td>Called when a trackball motion event occurs.
212 * </td>
213 * </tr>
214 * <tr>
215 * <td><code>{@link #onTouchEvent}</code></td>
216 * <td>Called when a touch screen motion event occurs.
217 * </td>
218 * </tr>
219 *
220 * <tr>
221 * <td rowspan="2">Focus</td>
222 * <td><code>{@link #onFocusChanged}</code></td>
223 * <td>Called when the view gains or loses focus.
224 * </td>
225 * </tr>
226 *
227 * <tr>
228 * <td><code>{@link #onWindowFocusChanged}</code></td>
229 * <td>Called when the window containing the view gains or loses focus.
230 * </td>
231 * </tr>
232 *
233 * <tr>
234 * <td rowspan="3">Attaching</td>
235 * <td><code>{@link #onAttachedToWindow()}</code></td>
236 * <td>Called when the view is attached to a window.
237 * </td>
238 * </tr>
239 *
240 * <tr>
241 * <td><code>{@link #onDetachedFromWindow}</code></td>
242 * <td>Called when the view is detached from its window.
243 * </td>
244 * </tr>
245 *
246 * <tr>
247 * <td><code>{@link #onWindowVisibilityChanged}</code></td>
248 * <td>Called when the visibility of the window containing the view
249 * has changed.
250 * </td>
251 * </tr>
252 * </tbody>
253 *
254 * </table>
255 * </p>
256 *
257 * <a name="IDs"></a>
258 * <h3>IDs</h3>
259 * Views may have an integer id associated with them. These ids are typically
260 * assigned in the layout XML files, and are used to find specific views within
261 * the view tree. A common pattern is to:
262 * <ul>
263 * <li>Define a Button in the layout file and assign it a unique ID.
264 * <pre>
Gilles Debunne0243caf2010-08-24 23:06:35 -0700265 * &lt;Button
266 * android:id="@+id/my_button"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 * android:layout_width="wrap_content"
268 * android:layout_height="wrap_content"
269 * android:text="@string/my_button_text"/&gt;
270 * </pre></li>
271 * <li>From the onCreate method of an Activity, find the Button
272 * <pre class="prettyprint">
273 * Button myButton = (Button) findViewById(R.id.my_button);
274 * </pre></li>
275 * </ul>
276 * <p>
277 * View IDs need not be unique throughout the tree, but it is good practice to
278 * ensure that they are at least unique within the part of the tree you are
279 * searching.
280 * </p>
281 *
282 * <a name="Position"></a>
283 * <h3>Position</h3>
284 * <p>
285 * The geometry of a view is that of a rectangle. A view has a location,
286 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
287 * two dimensions, expressed as a width and a height. The unit for location
288 * and dimensions is the pixel.
289 * </p>
290 *
291 * <p>
292 * It is possible to retrieve the location of a view by invoking the methods
293 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
294 * coordinate of the rectangle representing the view. The latter returns the
295 * top, or Y, coordinate of the rectangle representing the view. These methods
296 * both return the location of the view relative to its parent. For instance,
297 * when getLeft() returns 20, that means the view is located 20 pixels to the
298 * right of the left edge of its direct parent.
299 * </p>
300 *
301 * <p>
302 * In addition, several convenience methods are offered to avoid unnecessary
303 * computations, namely {@link #getRight()} and {@link #getBottom()}.
304 * These methods return the coordinates of the right and bottom edges of the
305 * rectangle representing the view. For instance, calling {@link #getRight()}
306 * is similar to the following computation: <code>getLeft() + getWidth()</code>
307 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
308 * </p>
309 *
310 * <a name="SizePaddingMargins"></a>
311 * <h3>Size, padding and margins</h3>
312 * <p>
313 * The size of a view is expressed with a width and a height. A view actually
314 * possess two pairs of width and height values.
315 * </p>
316 *
317 * <p>
318 * The first pair is known as <em>measured width</em> and
319 * <em>measured height</em>. These dimensions define how big a view wants to be
320 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
321 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
322 * and {@link #getMeasuredHeight()}.
323 * </p>
324 *
325 * <p>
326 * The second pair is simply known as <em>width</em> and <em>height</em>, or
327 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
328 * dimensions define the actual size of the view on screen, at drawing time and
329 * after layout. These values may, but do not have to, be different from the
330 * measured width and height. The width and height can be obtained by calling
331 * {@link #getWidth()} and {@link #getHeight()}.
332 * </p>
333 *
334 * <p>
335 * To measure its dimensions, a view takes into account its padding. The padding
336 * is expressed in pixels for the left, top, right and bottom parts of the view.
337 * Padding can be used to offset the content of the view by a specific amount of
338 * pixels. For instance, a left padding of 2 will push the view's content by
339 * 2 pixels to the right of the left edge. Padding can be set using the
340 * {@link #setPadding(int, int, int, int)} method and queried by calling
341 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
342 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
343 * </p>
344 *
345 * <p>
346 * Even though a view can define a padding, it does not provide any support for
347 * margins. However, view groups provide such a support. Refer to
348 * {@link android.view.ViewGroup} and
349 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
350 * </p>
351 *
352 * <a name="Layout"></a>
353 * <h3>Layout</h3>
354 * <p>
355 * Layout is a two pass process: a measure pass and a layout pass. The measuring
356 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
357 * of the view tree. Each view pushes dimension specifications down the tree
358 * during the recursion. At the end of the measure pass, every view has stored
359 * its measurements. The second pass happens in
360 * {@link #layout(int,int,int,int)} and is also top-down. During
361 * this pass each parent is responsible for positioning all of its children
362 * using the sizes computed in the measure pass.
363 * </p>
364 *
365 * <p>
366 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
367 * {@link #getMeasuredHeight()} values must be set, along with those for all of
368 * that view's descendants. A view's measured width and measured height values
369 * must respect the constraints imposed by the view's parents. This guarantees
370 * that at the end of the measure pass, all parents accept all of their
371 * children's measurements. A parent view may call measure() more than once on
372 * its children. For example, the parent may measure each child once with
373 * unspecified dimensions to find out how big they want to be, then call
374 * measure() on them again with actual numbers if the sum of all the children's
375 * unconstrained sizes is too big or too small.
376 * </p>
377 *
378 * <p>
379 * The measure pass uses two classes to communicate dimensions. The
380 * {@link MeasureSpec} class is used by views to tell their parents how they
381 * want to be measured and positioned. The base LayoutParams class just
382 * describes how big the view wants to be for both width and height. For each
383 * dimension, it can specify one of:
384 * <ul>
385 * <li> an exact number
Romain Guy980a9382010-01-08 15:06:28 -0800386 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 * (minus padding)
388 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
389 * enclose its content (plus padding).
390 * </ul>
391 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
392 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
393 * an X and Y value.
394 * </p>
395 *
396 * <p>
397 * MeasureSpecs are used to push requirements down the tree from parent to
398 * child. A MeasureSpec can be in one of three modes:
399 * <ul>
400 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
401 * of a child view. For example, a LinearLayout may call measure() on its child
402 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
403 * tall the child view wants to be given a width of 240 pixels.
404 * <li>EXACTLY: This is used by the parent to impose an exact size on the
405 * child. The child must use this size, and guarantee that all of its
406 * descendants will fit within this size.
407 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
408 * child. The child must gurantee that it and all of its descendants will fit
409 * within this size.
410 * </ul>
411 * </p>
412 *
413 * <p>
414 * To intiate a layout, call {@link #requestLayout}. This method is typically
415 * called by a view on itself when it believes that is can no longer fit within
416 * its current bounds.
417 * </p>
418 *
419 * <a name="Drawing"></a>
420 * <h3>Drawing</h3>
421 * <p>
422 * Drawing is handled by walking the tree and rendering each view that
423 * intersects the the invalid region. Because the tree is traversed in-order,
424 * this means that parents will draw before (i.e., behind) their children, with
425 * siblings drawn in the order they appear in the tree.
426 * If you set a background drawable for a View, then the View will draw it for you
427 * before calling back to its <code>onDraw()</code> method.
428 * </p>
429 *
430 * <p>
Romain Guy8506ab42009-06-11 17:35:47 -0700431 * Note that the framework will not draw views that are not in the invalid region.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 * </p>
433 *
434 * <p>
435 * To force a view to draw, call {@link #invalidate()}.
436 * </p>
437 *
438 * <a name="EventHandlingThreading"></a>
439 * <h3>Event Handling and Threading</h3>
440 * <p>
441 * The basic cycle of a view is as follows:
442 * <ol>
443 * <li>An event comes in and is dispatched to the appropriate view. The view
444 * handles the event and notifies any listeners.</li>
445 * <li>If in the course of processing the event, the view's bounds may need
446 * to be changed, the view will call {@link #requestLayout()}.</li>
447 * <li>Similarly, if in the course of processing the event the view's appearance
448 * may need to be changed, the view will call {@link #invalidate()}.</li>
449 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
450 * the framework will take care of measuring, laying out, and drawing the tree
451 * as appropriate.</li>
452 * </ol>
453 * </p>
454 *
455 * <p><em>Note: The entire view tree is single threaded. You must always be on
456 * the UI thread when calling any method on any view.</em>
457 * If you are doing work on other threads and want to update the state of a view
458 * from that thread, you should use a {@link Handler}.
459 * </p>
460 *
461 * <a name="FocusHandling"></a>
462 * <h3>Focus Handling</h3>
463 * <p>
464 * The framework will handle routine focus movement in response to user input.
465 * This includes changing the focus as views are removed or hidden, or as new
466 * views become available. Views indicate their willingness to take focus
467 * through the {@link #isFocusable} method. To change whether a view can take
468 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
469 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
470 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
471 * </p>
472 * <p>
473 * Focus movement is based on an algorithm which finds the nearest neighbor in a
474 * given direction. In rare cases, the default algorithm may not match the
475 * intended behavior of the developer. In these situations, you can provide
476 * explicit overrides by using these XML attributes in the layout file:
477 * <pre>
478 * nextFocusDown
479 * nextFocusLeft
480 * nextFocusRight
481 * nextFocusUp
482 * </pre>
483 * </p>
484 *
485 *
486 * <p>
487 * To get a particular view to take focus, call {@link #requestFocus()}.
488 * </p>
489 *
490 * <a name="TouchMode"></a>
491 * <h3>Touch Mode</h3>
492 * <p>
493 * When a user is navigating a user interface via directional keys such as a D-pad, it is
494 * necessary to give focus to actionable items such as buttons so the user can see
495 * what will take input. If the device has touch capabilities, however, and the user
496 * begins interacting with the interface by touching it, it is no longer necessary to
497 * always highlight, or give focus to, a particular view. This motivates a mode
498 * for interaction named 'touch mode'.
499 * </p>
500 * <p>
501 * For a touch capable device, once the user touches the screen, the device
502 * will enter touch mode. From this point onward, only views for which
503 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
504 * Other views that are touchable, like buttons, will not take focus when touched; they will
505 * only fire the on click listeners.
506 * </p>
507 * <p>
508 * Any time a user hits a directional key, such as a D-pad direction, the view device will
509 * exit touch mode, and find a view to take focus, so that the user may resume interacting
510 * with the user interface without touching the screen again.
511 * </p>
512 * <p>
513 * The touch mode state is maintained across {@link android.app.Activity}s. Call
514 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
515 * </p>
516 *
517 * <a name="Scrolling"></a>
518 * <h3>Scrolling</h3>
519 * <p>
520 * The framework provides basic support for views that wish to internally
521 * scroll their content. This includes keeping track of the X and Y scroll
522 * offset as well as mechanisms for drawing scrollbars. See
Mike Cleronf116bf82009-09-27 19:14:12 -0700523 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
524 * {@link #awakenScrollBars()} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 * </p>
526 *
527 * <a name="Tags"></a>
528 * <h3>Tags</h3>
529 * <p>
530 * Unlike IDs, tags are not used to identify views. Tags are essentially an
531 * extra piece of information that can be associated with a view. They are most
532 * often used as a convenience to store data related to views in the views
533 * themselves rather than by putting them in a separate structure.
534 * </p>
535 *
536 * <a name="Animation"></a>
537 * <h3>Animation</h3>
538 * <p>
539 * You can attach an {@link Animation} object to a view using
540 * {@link #setAnimation(Animation)} or
541 * {@link #startAnimation(Animation)}. The animation can alter the scale,
542 * rotation, translation and alpha of a view over time. If the animation is
543 * attached to a view that has children, the animation will affect the entire
544 * subtree rooted by that node. When an animation is started, the framework will
545 * take care of redrawing the appropriate views until the animation completes.
546 * </p>
547 *
Jeff Brown85a31762010-09-01 17:01:00 -0700548 * <a name="Security"></a>
549 * <h3>Security</h3>
550 * <p>
551 * Sometimes it is essential that an application be able to verify that an action
552 * is being performed with the full knowledge and consent of the user, such as
553 * granting a permission request, making a purchase or clicking on an advertisement.
554 * Unfortunately, a malicious application could try to spoof the user into
555 * performing these actions, unaware, by concealing the intended purpose of the view.
556 * As a remedy, the framework offers a touch filtering mechanism that can be used to
557 * improve the security of views that provide access to sensitive functionality.
558 * </p><p>
559 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
560 * andoird:filterTouchesWhenObscured attribute to true. When enabled, the framework
561 * will discard touches that are received whenever the view's window is obscured by
562 * another visible window. As a result, the view will not receive touches whenever a
563 * toast, dialog or other window appears above the view's window.
564 * </p><p>
565 * For more fine-grained control over security, consider overriding the
566 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
567 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
568 * </p>
569 *
Romain Guyd6a463a2009-05-21 23:10:10 -0700570 * @attr ref android.R.styleable#View_background
571 * @attr ref android.R.styleable#View_clickable
572 * @attr ref android.R.styleable#View_contentDescription
573 * @attr ref android.R.styleable#View_drawingCacheQuality
574 * @attr ref android.R.styleable#View_duplicateParentState
575 * @attr ref android.R.styleable#View_id
576 * @attr ref android.R.styleable#View_fadingEdge
577 * @attr ref android.R.styleable#View_fadingEdgeLength
Jeff Brown85a31762010-09-01 17:01:00 -0700578 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 * @attr ref android.R.styleable#View_fitsSystemWindows
Romain Guyd6a463a2009-05-21 23:10:10 -0700580 * @attr ref android.R.styleable#View_isScrollContainer
581 * @attr ref android.R.styleable#View_focusable
582 * @attr ref android.R.styleable#View_focusableInTouchMode
583 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
584 * @attr ref android.R.styleable#View_keepScreenOn
585 * @attr ref android.R.styleable#View_longClickable
586 * @attr ref android.R.styleable#View_minHeight
587 * @attr ref android.R.styleable#View_minWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 * @attr ref android.R.styleable#View_nextFocusDown
589 * @attr ref android.R.styleable#View_nextFocusLeft
590 * @attr ref android.R.styleable#View_nextFocusRight
591 * @attr ref android.R.styleable#View_nextFocusUp
Romain Guyd6a463a2009-05-21 23:10:10 -0700592 * @attr ref android.R.styleable#View_onClick
593 * @attr ref android.R.styleable#View_padding
594 * @attr ref android.R.styleable#View_paddingBottom
595 * @attr ref android.R.styleable#View_paddingLeft
596 * @attr ref android.R.styleable#View_paddingRight
597 * @attr ref android.R.styleable#View_paddingTop
598 * @attr ref android.R.styleable#View_saveEnabled
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 * @attr ref android.R.styleable#View_scrollX
600 * @attr ref android.R.styleable#View_scrollY
Romain Guyd6a463a2009-05-21 23:10:10 -0700601 * @attr ref android.R.styleable#View_scrollbarSize
602 * @attr ref android.R.styleable#View_scrollbarStyle
603 * @attr ref android.R.styleable#View_scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -0700604 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
605 * @attr ref android.R.styleable#View_scrollbarFadeDuration
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
607 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 * @attr ref android.R.styleable#View_scrollbarThumbVertical
609 * @attr ref android.R.styleable#View_scrollbarTrackVertical
610 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
611 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
Romain Guyd6a463a2009-05-21 23:10:10 -0700612 * @attr ref android.R.styleable#View_soundEffectsEnabled
613 * @attr ref android.R.styleable#View_tag
614 * @attr ref android.R.styleable#View_visibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 *
616 * @see android.view.ViewGroup
617 */
svetoslavganov75986cf2009-05-14 22:28:01 -0700618public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 private static final boolean DBG = false;
620
621 /**
622 * The logging tag used by this class with android.util.Log.
623 */
624 protected static final String VIEW_LOG_TAG = "View";
625
626 /**
627 * Used to mark a View that has no ID.
628 */
629 public static final int NO_ID = -1;
630
631 /**
632 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
633 * calling setFlags.
634 */
635 private static final int NOT_FOCUSABLE = 0x00000000;
636
637 /**
638 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
639 * setFlags.
640 */
641 private static final int FOCUSABLE = 0x00000001;
642
643 /**
644 * Mask for use with setFlags indicating bits used for focus.
645 */
646 private static final int FOCUSABLE_MASK = 0x00000001;
647
648 /**
649 * This view will adjust its padding to fit sytem windows (e.g. status bar)
650 */
651 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
652
653 /**
654 * This view is visible. Use with {@link #setVisibility}.
655 */
656 public static final int VISIBLE = 0x00000000;
657
658 /**
659 * This view is invisible, but it still takes up space for layout purposes.
660 * Use with {@link #setVisibility}.
661 */
662 public static final int INVISIBLE = 0x00000004;
663
664 /**
665 * This view is invisible, and it doesn't take any space for layout
666 * purposes. Use with {@link #setVisibility}.
667 */
668 public static final int GONE = 0x00000008;
669
670 /**
671 * Mask for use with setFlags indicating bits used for visibility.
672 * {@hide}
673 */
674 static final int VISIBILITY_MASK = 0x0000000C;
675
676 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
677
678 /**
679 * This view is enabled. Intrepretation varies by subclass.
680 * Use with ENABLED_MASK when calling setFlags.
681 * {@hide}
682 */
683 static final int ENABLED = 0x00000000;
684
685 /**
686 * This view is disabled. Intrepretation varies by subclass.
687 * Use with ENABLED_MASK when calling setFlags.
688 * {@hide}
689 */
690 static final int DISABLED = 0x00000020;
691
692 /**
693 * Mask for use with setFlags indicating bits used for indicating whether
694 * this view is enabled
695 * {@hide}
696 */
697 static final int ENABLED_MASK = 0x00000020;
698
699 /**
700 * This view won't draw. {@link #onDraw} won't be called and further
701 * optimizations
702 * will be performed. It is okay to have this flag set and a background.
703 * Use with DRAW_MASK when calling setFlags.
704 * {@hide}
705 */
706 static final int WILL_NOT_DRAW = 0x00000080;
707
708 /**
709 * Mask for use with setFlags indicating bits used for indicating whether
710 * this view is will draw
711 * {@hide}
712 */
713 static final int DRAW_MASK = 0x00000080;
714
715 /**
716 * <p>This view doesn't show scrollbars.</p>
717 * {@hide}
718 */
719 static final int SCROLLBARS_NONE = 0x00000000;
720
721 /**
722 * <p>This view shows horizontal scrollbars.</p>
723 * {@hide}
724 */
725 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
726
727 /**
728 * <p>This view shows vertical scrollbars.</p>
729 * {@hide}
730 */
731 static final int SCROLLBARS_VERTICAL = 0x00000200;
732
733 /**
734 * <p>Mask for use with setFlags indicating bits used for indicating which
735 * scrollbars are enabled.</p>
736 * {@hide}
737 */
738 static final int SCROLLBARS_MASK = 0x00000300;
739
Jeff Brown85a31762010-09-01 17:01:00 -0700740 /**
741 * Indicates that the view should filter touches when its window is obscured.
742 * Refer to the class comments for more information about this security feature.
743 * {@hide}
744 */
745 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
746
747 // note flag value 0x00000800 is now available for next flags...
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748
749 /**
750 * <p>This view doesn't show fading edges.</p>
751 * {@hide}
752 */
753 static final int FADING_EDGE_NONE = 0x00000000;
754
755 /**
756 * <p>This view shows horizontal fading edges.</p>
757 * {@hide}
758 */
759 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
760
761 /**
762 * <p>This view shows vertical fading edges.</p>
763 * {@hide}
764 */
765 static final int FADING_EDGE_VERTICAL = 0x00002000;
766
767 /**
768 * <p>Mask for use with setFlags indicating bits used for indicating which
769 * fading edges are enabled.</p>
770 * {@hide}
771 */
772 static final int FADING_EDGE_MASK = 0x00003000;
773
774 /**
775 * <p>Indicates this view can be clicked. When clickable, a View reacts
776 * to clicks by notifying the OnClickListener.<p>
777 * {@hide}
778 */
779 static final int CLICKABLE = 0x00004000;
780
781 /**
782 * <p>Indicates this view is caching its drawing into a bitmap.</p>
783 * {@hide}
784 */
785 static final int DRAWING_CACHE_ENABLED = 0x00008000;
786
787 /**
788 * <p>Indicates that no icicle should be saved for this view.<p>
789 * {@hide}
790 */
791 static final int SAVE_DISABLED = 0x000010000;
792
793 /**
794 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
795 * property.</p>
796 * {@hide}
797 */
798 static final int SAVE_DISABLED_MASK = 0x000010000;
799
800 /**
801 * <p>Indicates that no drawing cache should ever be created for this view.<p>
802 * {@hide}
803 */
804 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
805
806 /**
807 * <p>Indicates this view can take / keep focus when int touch mode.</p>
808 * {@hide}
809 */
810 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
811
812 /**
813 * <p>Enables low quality mode for the drawing cache.</p>
814 */
815 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
816
817 /**
818 * <p>Enables high quality mode for the drawing cache.</p>
819 */
820 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
821
822 /**
823 * <p>Enables automatic quality mode for the drawing cache.</p>
824 */
825 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
826
827 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
828 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
829 };
830
831 /**
832 * <p>Mask for use with setFlags indicating bits used for the cache
833 * quality property.</p>
834 * {@hide}
835 */
836 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
837
838 /**
839 * <p>
840 * Indicates this view can be long clicked. When long clickable, a View
841 * reacts to long clicks by notifying the OnLongClickListener or showing a
842 * context menu.
843 * </p>
844 * {@hide}
845 */
846 static final int LONG_CLICKABLE = 0x00200000;
847
848 /**
849 * <p>Indicates that this view gets its drawable states from its direct parent
850 * and ignores its original internal states.</p>
851 *
852 * @hide
853 */
854 static final int DUPLICATE_PARENT_STATE = 0x00400000;
855
856 /**
857 * The scrollbar style to display the scrollbars inside the content area,
858 * without increasing the padding. The scrollbars will be overlaid with
859 * translucency on the view's content.
860 */
861 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
862
863 /**
864 * The scrollbar style to display the scrollbars inside the padded area,
865 * increasing the padding of the view. The scrollbars will not overlap the
866 * content area of the view.
867 */
868 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
869
870 /**
871 * The scrollbar style to display the scrollbars at the edge of the view,
872 * without increasing the padding. The scrollbars will be overlaid with
873 * translucency.
874 */
875 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
876
877 /**
878 * The scrollbar style to display the scrollbars at the edge of the view,
879 * increasing the padding of the view. The scrollbars will only overlap the
880 * background, if any.
881 */
882 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
883
884 /**
885 * Mask to check if the scrollbar style is overlay or inset.
886 * {@hide}
887 */
888 static final int SCROLLBARS_INSET_MASK = 0x01000000;
889
890 /**
891 * Mask to check if the scrollbar style is inside or outside.
892 * {@hide}
893 */
894 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
895
896 /**
897 * Mask for scrollbar style.
898 * {@hide}
899 */
900 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
901
902 /**
903 * View flag indicating that the screen should remain on while the
904 * window containing this view is visible to the user. This effectively
905 * takes care of automatically setting the WindowManager's
906 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
907 */
908 public static final int KEEP_SCREEN_ON = 0x04000000;
909
910 /**
911 * View flag indicating whether this view should have sound effects enabled
912 * for events such as clicking and touching.
913 */
914 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
915
916 /**
917 * View flag indicating whether this view should have haptic feedback
918 * enabled for events such as long presses.
919 */
920 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
921
922 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700923 * <p>Indicates that the view hierarchy should stop saving state when
924 * it reaches this view. If state saving is initiated immediately at
925 * the view, it will be allowed.
926 * {@hide}
927 */
928 static final int PARENT_SAVE_DISABLED = 0x20000000;
929
930 /**
931 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
932 * {@hide}
933 */
934 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
935
936 /**
svetoslavganov75986cf2009-05-14 22:28:01 -0700937 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
938 * should add all focusable Views regardless if they are focusable in touch mode.
939 */
940 public static final int FOCUSABLES_ALL = 0x00000000;
941
942 /**
943 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
944 * should add only Views focusable in touch mode.
945 */
946 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
947
948 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 * Use with {@link #focusSearch}. Move focus to the previous selectable
950 * item.
951 */
952 public static final int FOCUS_BACKWARD = 0x00000001;
953
954 /**
955 * Use with {@link #focusSearch}. Move focus to the next selectable
956 * item.
957 */
958 public static final int FOCUS_FORWARD = 0x00000002;
959
960 /**
961 * Use with {@link #focusSearch}. Move focus to the left.
962 */
963 public static final int FOCUS_LEFT = 0x00000011;
964
965 /**
966 * Use with {@link #focusSearch}. Move focus up.
967 */
968 public static final int FOCUS_UP = 0x00000021;
969
970 /**
971 * Use with {@link #focusSearch}. Move focus to the right.
972 */
973 public static final int FOCUS_RIGHT = 0x00000042;
974
975 /**
976 * Use with {@link #focusSearch}. Move focus down.
977 */
978 public static final int FOCUS_DOWN = 0x00000082;
979
980 /**
981 * Base View state sets
982 */
983 // Singles
984 /**
985 * Indicates the view has no states set. States are used with
986 * {@link android.graphics.drawable.Drawable} to change the drawing of the
987 * view depending on its state.
988 *
989 * @see android.graphics.drawable.Drawable
990 * @see #getDrawableState()
991 */
992 protected static final int[] EMPTY_STATE_SET = {};
993 /**
994 * Indicates the view is enabled. States are used with
995 * {@link android.graphics.drawable.Drawable} to change the drawing of the
996 * view depending on its state.
997 *
998 * @see android.graphics.drawable.Drawable
999 * @see #getDrawableState()
1000 */
1001 protected static final int[] ENABLED_STATE_SET = {R.attr.state_enabled};
1002 /**
1003 * Indicates the view is focused. States are used with
1004 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1005 * view depending on its state.
1006 *
1007 * @see android.graphics.drawable.Drawable
1008 * @see #getDrawableState()
1009 */
1010 protected static final int[] FOCUSED_STATE_SET = {R.attr.state_focused};
1011 /**
1012 * Indicates the view is selected. States are used with
1013 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1014 * view depending on its state.
1015 *
1016 * @see android.graphics.drawable.Drawable
1017 * @see #getDrawableState()
1018 */
1019 protected static final int[] SELECTED_STATE_SET = {R.attr.state_selected};
1020 /**
1021 * Indicates the view is pressed. States are used with
1022 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1023 * view depending on its state.
1024 *
1025 * @see android.graphics.drawable.Drawable
1026 * @see #getDrawableState()
1027 * @hide
1028 */
1029 protected static final int[] PRESSED_STATE_SET = {R.attr.state_pressed};
1030 /**
1031 * Indicates the view's window has focus. States are used with
1032 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1033 * view depending on its state.
1034 *
1035 * @see android.graphics.drawable.Drawable
1036 * @see #getDrawableState()
1037 */
1038 protected static final int[] WINDOW_FOCUSED_STATE_SET =
1039 {R.attr.state_window_focused};
1040 // Doubles
1041 /**
1042 * Indicates the view is enabled and has the focus.
1043 *
1044 * @see #ENABLED_STATE_SET
1045 * @see #FOCUSED_STATE_SET
1046 */
1047 protected static final int[] ENABLED_FOCUSED_STATE_SET =
1048 stateSetUnion(ENABLED_STATE_SET, FOCUSED_STATE_SET);
1049 /**
1050 * Indicates the view is enabled and selected.
1051 *
1052 * @see #ENABLED_STATE_SET
1053 * @see #SELECTED_STATE_SET
1054 */
1055 protected static final int[] ENABLED_SELECTED_STATE_SET =
1056 stateSetUnion(ENABLED_STATE_SET, SELECTED_STATE_SET);
1057 /**
1058 * Indicates the view is enabled and that its window has focus.
1059 *
1060 * @see #ENABLED_STATE_SET
1061 * @see #WINDOW_FOCUSED_STATE_SET
1062 */
1063 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET =
1064 stateSetUnion(ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1065 /**
1066 * Indicates the view is focused and selected.
1067 *
1068 * @see #FOCUSED_STATE_SET
1069 * @see #SELECTED_STATE_SET
1070 */
1071 protected static final int[] FOCUSED_SELECTED_STATE_SET =
1072 stateSetUnion(FOCUSED_STATE_SET, SELECTED_STATE_SET);
1073 /**
1074 * Indicates the view has the focus and that its window has the focus.
1075 *
1076 * @see #FOCUSED_STATE_SET
1077 * @see #WINDOW_FOCUSED_STATE_SET
1078 */
1079 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET =
1080 stateSetUnion(FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1081 /**
1082 * Indicates the view is selected and that its window has the focus.
1083 *
1084 * @see #SELECTED_STATE_SET
1085 * @see #WINDOW_FOCUSED_STATE_SET
1086 */
1087 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET =
1088 stateSetUnion(SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1089 // Triples
1090 /**
1091 * Indicates the view is enabled, focused and selected.
1092 *
1093 * @see #ENABLED_STATE_SET
1094 * @see #FOCUSED_STATE_SET
1095 * @see #SELECTED_STATE_SET
1096 */
1097 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET =
1098 stateSetUnion(ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1099 /**
1100 * Indicates the view is enabled, focused and its window has the focus.
1101 *
1102 * @see #ENABLED_STATE_SET
1103 * @see #FOCUSED_STATE_SET
1104 * @see #WINDOW_FOCUSED_STATE_SET
1105 */
1106 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1107 stateSetUnion(ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1108 /**
1109 * Indicates the view is enabled, selected and its window has the focus.
1110 *
1111 * @see #ENABLED_STATE_SET
1112 * @see #SELECTED_STATE_SET
1113 * @see #WINDOW_FOCUSED_STATE_SET
1114 */
1115 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1116 stateSetUnion(ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1117 /**
1118 * Indicates the view is focused, selected and its window has the focus.
1119 *
1120 * @see #FOCUSED_STATE_SET
1121 * @see #SELECTED_STATE_SET
1122 * @see #WINDOW_FOCUSED_STATE_SET
1123 */
1124 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1125 stateSetUnion(FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1126 /**
1127 * Indicates the view is enabled, focused, selected and its window
1128 * has the focus.
1129 *
1130 * @see #ENABLED_STATE_SET
1131 * @see #FOCUSED_STATE_SET
1132 * @see #SELECTED_STATE_SET
1133 * @see #WINDOW_FOCUSED_STATE_SET
1134 */
1135 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1136 stateSetUnion(ENABLED_FOCUSED_SELECTED_STATE_SET,
1137 WINDOW_FOCUSED_STATE_SET);
1138
1139 /**
1140 * Indicates the view is pressed and its window has the focus.
1141 *
1142 * @see #PRESSED_STATE_SET
1143 * @see #WINDOW_FOCUSED_STATE_SET
1144 */
1145 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET =
1146 stateSetUnion(PRESSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1147
1148 /**
1149 * Indicates the view is pressed and selected.
1150 *
1151 * @see #PRESSED_STATE_SET
1152 * @see #SELECTED_STATE_SET
1153 */
1154 protected static final int[] PRESSED_SELECTED_STATE_SET =
1155 stateSetUnion(PRESSED_STATE_SET, SELECTED_STATE_SET);
1156
1157 /**
1158 * Indicates the view is pressed, selected and its window has the focus.
1159 *
1160 * @see #PRESSED_STATE_SET
1161 * @see #SELECTED_STATE_SET
1162 * @see #WINDOW_FOCUSED_STATE_SET
1163 */
1164 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1165 stateSetUnion(PRESSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1166
1167 /**
1168 * Indicates the view is pressed and focused.
1169 *
1170 * @see #PRESSED_STATE_SET
1171 * @see #FOCUSED_STATE_SET
1172 */
1173 protected static final int[] PRESSED_FOCUSED_STATE_SET =
1174 stateSetUnion(PRESSED_STATE_SET, FOCUSED_STATE_SET);
1175
1176 /**
1177 * Indicates the view is pressed, focused and its window has the focus.
1178 *
1179 * @see #PRESSED_STATE_SET
1180 * @see #FOCUSED_STATE_SET
1181 * @see #WINDOW_FOCUSED_STATE_SET
1182 */
1183 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1184 stateSetUnion(PRESSED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1185
1186 /**
1187 * Indicates the view is pressed, focused and selected.
1188 *
1189 * @see #PRESSED_STATE_SET
1190 * @see #SELECTED_STATE_SET
1191 * @see #FOCUSED_STATE_SET
1192 */
1193 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET =
1194 stateSetUnion(PRESSED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1195
1196 /**
1197 * Indicates the view is pressed, focused, selected and its window has the focus.
1198 *
1199 * @see #PRESSED_STATE_SET
1200 * @see #FOCUSED_STATE_SET
1201 * @see #SELECTED_STATE_SET
1202 * @see #WINDOW_FOCUSED_STATE_SET
1203 */
1204 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1205 stateSetUnion(PRESSED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1206
1207 /**
1208 * Indicates the view is pressed and enabled.
1209 *
1210 * @see #PRESSED_STATE_SET
1211 * @see #ENABLED_STATE_SET
1212 */
1213 protected static final int[] PRESSED_ENABLED_STATE_SET =
1214 stateSetUnion(PRESSED_STATE_SET, ENABLED_STATE_SET);
1215
1216 /**
1217 * Indicates the view is pressed, enabled and its window has the focus.
1218 *
1219 * @see #PRESSED_STATE_SET
1220 * @see #ENABLED_STATE_SET
1221 * @see #WINDOW_FOCUSED_STATE_SET
1222 */
1223 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET =
1224 stateSetUnion(PRESSED_ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1225
1226 /**
1227 * Indicates the view is pressed, enabled and selected.
1228 *
1229 * @see #PRESSED_STATE_SET
1230 * @see #ENABLED_STATE_SET
1231 * @see #SELECTED_STATE_SET
1232 */
1233 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET =
1234 stateSetUnion(PRESSED_ENABLED_STATE_SET, SELECTED_STATE_SET);
1235
1236 /**
1237 * Indicates the view is pressed, enabled, selected and its window has the
1238 * focus.
1239 *
1240 * @see #PRESSED_STATE_SET
1241 * @see #ENABLED_STATE_SET
1242 * @see #SELECTED_STATE_SET
1243 * @see #WINDOW_FOCUSED_STATE_SET
1244 */
1245 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1246 stateSetUnion(PRESSED_ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1247
1248 /**
1249 * Indicates the view is pressed, enabled and focused.
1250 *
1251 * @see #PRESSED_STATE_SET
1252 * @see #ENABLED_STATE_SET
1253 * @see #FOCUSED_STATE_SET
1254 */
1255 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET =
1256 stateSetUnion(PRESSED_ENABLED_STATE_SET, FOCUSED_STATE_SET);
1257
1258 /**
1259 * Indicates the view is pressed, enabled, focused and its window has the
1260 * focus.
1261 *
1262 * @see #PRESSED_STATE_SET
1263 * @see #ENABLED_STATE_SET
1264 * @see #FOCUSED_STATE_SET
1265 * @see #WINDOW_FOCUSED_STATE_SET
1266 */
1267 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
1268 stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1269
1270 /**
1271 * Indicates the view is pressed, enabled, focused and selected.
1272 *
1273 * @see #PRESSED_STATE_SET
1274 * @see #ENABLED_STATE_SET
1275 * @see #SELECTED_STATE_SET
1276 * @see #FOCUSED_STATE_SET
1277 */
1278 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET =
1279 stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
1280
1281 /**
1282 * Indicates the view is pressed, enabled, focused, selected and its window
1283 * has the focus.
1284 *
1285 * @see #PRESSED_STATE_SET
1286 * @see #ENABLED_STATE_SET
1287 * @see #SELECTED_STATE_SET
1288 * @see #FOCUSED_STATE_SET
1289 * @see #WINDOW_FOCUSED_STATE_SET
1290 */
1291 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
1292 stateSetUnion(PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
1293
1294 /**
1295 * The order here is very important to {@link #getDrawableState()}
1296 */
1297 private static final int[][] VIEW_STATE_SETS = {
1298 EMPTY_STATE_SET, // 0 0 0 0 0
1299 WINDOW_FOCUSED_STATE_SET, // 0 0 0 0 1
1300 SELECTED_STATE_SET, // 0 0 0 1 0
1301 SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 0 1 1
1302 FOCUSED_STATE_SET, // 0 0 1 0 0
1303 FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 0 1
1304 FOCUSED_SELECTED_STATE_SET, // 0 0 1 1 0
1305 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 1 1
1306 ENABLED_STATE_SET, // 0 1 0 0 0
1307 ENABLED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 0 1
1308 ENABLED_SELECTED_STATE_SET, // 0 1 0 1 0
1309 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 1 1
1310 ENABLED_FOCUSED_STATE_SET, // 0 1 1 0 0
1311 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 0 1
1312 ENABLED_FOCUSED_SELECTED_STATE_SET, // 0 1 1 1 0
1313 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 1 1
1314 PRESSED_STATE_SET, // 1 0 0 0 0
1315 PRESSED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 0 1
1316 PRESSED_SELECTED_STATE_SET, // 1 0 0 1 0
1317 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 1 1
1318 PRESSED_FOCUSED_STATE_SET, // 1 0 1 0 0
1319 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 0 1
1320 PRESSED_FOCUSED_SELECTED_STATE_SET, // 1 0 1 1 0
1321 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 1 1
1322 PRESSED_ENABLED_STATE_SET, // 1 1 0 0 0
1323 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 0 1
1324 PRESSED_ENABLED_SELECTED_STATE_SET, // 1 1 0 1 0
1325 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 1 1
1326 PRESSED_ENABLED_FOCUSED_STATE_SET, // 1 1 1 0 0
1327 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 0 1
1328 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, // 1 1 1 1 0
1329 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 1 1
1330 };
1331
1332 /**
1333 * Used by views that contain lists of items. This state indicates that
1334 * the view is showing the last item.
1335 * @hide
1336 */
1337 protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1338 /**
1339 * Used by views that contain lists of items. This state indicates that
1340 * the view is showing the first item.
1341 * @hide
1342 */
1343 protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1344 /**
1345 * Used by views that contain lists of items. This state indicates that
1346 * the view is showing the middle item.
1347 * @hide
1348 */
1349 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1350 /**
1351 * Used by views that contain lists of items. This state indicates that
1352 * the view is showing only one item.
1353 * @hide
1354 */
1355 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1356 /**
1357 * Used by views that contain lists of items. This state indicates that
1358 * the view is pressed and showing the last item.
1359 * @hide
1360 */
1361 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1362 /**
1363 * Used by views that contain lists of items. This state indicates that
1364 * the view is pressed and showing the first item.
1365 * @hide
1366 */
1367 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1368 /**
1369 * Used by views that contain lists of items. This state indicates that
1370 * the view is pressed and showing the middle item.
1371 * @hide
1372 */
1373 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1374 /**
1375 * Used by views that contain lists of items. This state indicates that
1376 * the view is pressed and showing only one item.
1377 * @hide
1378 */
1379 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1380
1381 /**
1382 * Temporary Rect currently for use in setBackground(). This will probably
1383 * be extended in the future to hold our own class with more than just
1384 * a Rect. :)
1385 */
1386 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
Romain Guyd90a3312009-05-06 14:54:28 -07001387
1388 /**
1389 * Map used to store views' tags.
1390 */
1391 private static WeakHashMap<View, SparseArray<Object>> sTags;
1392
1393 /**
1394 * Lock used to access sTags.
1395 */
1396 private static final Object sTagsLock = new Object();
1397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 /**
1399 * The animation currently associated with this view.
1400 * @hide
1401 */
1402 protected Animation mCurrentAnimation = null;
1403
1404 /**
1405 * Width as measured during measure pass.
1406 * {@hide}
1407 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001408 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 protected int mMeasuredWidth;
1410
1411 /**
1412 * Height as measured during measure pass.
1413 * {@hide}
1414 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001415 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 protected int mMeasuredHeight;
1417
1418 /**
1419 * The view's identifier.
1420 * {@hide}
1421 *
1422 * @see #setId(int)
1423 * @see #getId()
1424 */
1425 @ViewDebug.ExportedProperty(resolveId = true)
1426 int mID = NO_ID;
1427
1428 /**
1429 * The view's tag.
1430 * {@hide}
1431 *
1432 * @see #setTag(Object)
1433 * @see #getTag()
1434 */
1435 protected Object mTag;
1436
1437 // for mPrivateFlags:
1438 /** {@hide} */
1439 static final int WANTS_FOCUS = 0x00000001;
1440 /** {@hide} */
1441 static final int FOCUSED = 0x00000002;
1442 /** {@hide} */
1443 static final int SELECTED = 0x00000004;
1444 /** {@hide} */
1445 static final int IS_ROOT_NAMESPACE = 0x00000008;
1446 /** {@hide} */
1447 static final int HAS_BOUNDS = 0x00000010;
1448 /** {@hide} */
1449 static final int DRAWN = 0x00000020;
1450 /**
1451 * When this flag is set, this view is running an animation on behalf of its
1452 * children and should therefore not cancel invalidate requests, even if they
1453 * lie outside of this view's bounds.
1454 *
1455 * {@hide}
1456 */
1457 static final int DRAW_ANIMATION = 0x00000040;
1458 /** {@hide} */
1459 static final int SKIP_DRAW = 0x00000080;
1460 /** {@hide} */
1461 static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
1462 /** {@hide} */
1463 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1464 /** {@hide} */
1465 static final int DRAWABLE_STATE_DIRTY = 0x00000400;
1466 /** {@hide} */
1467 static final int MEASURED_DIMENSION_SET = 0x00000800;
1468 /** {@hide} */
1469 static final int FORCE_LAYOUT = 0x00001000;
Konstantin Lopyrevc6dc4572010-08-06 15:01:52 -07001470 /** {@hide} */
1471 static final int LAYOUT_REQUIRED = 0x00002000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472
1473 private static final int PRESSED = 0x00004000;
1474
1475 /** {@hide} */
1476 static final int DRAWING_CACHE_VALID = 0x00008000;
1477 /**
1478 * Flag used to indicate that this view should be drawn once more (and only once
1479 * more) after its animation has completed.
1480 * {@hide}
1481 */
1482 static final int ANIMATION_STARTED = 0x00010000;
1483
1484 private static final int SAVE_STATE_CALLED = 0x00020000;
1485
1486 /**
1487 * Indicates that the View returned true when onSetAlpha() was called and that
1488 * the alpha must be restored.
1489 * {@hide}
1490 */
1491 static final int ALPHA_SET = 0x00040000;
1492
1493 /**
1494 * Set by {@link #setScrollContainer(boolean)}.
1495 */
1496 static final int SCROLL_CONTAINER = 0x00080000;
1497
1498 /**
1499 * Set by {@link #setScrollContainer(boolean)}.
1500 */
1501 static final int SCROLL_CONTAINER_ADDED = 0x00100000;
1502
1503 /**
Romain Guy809a7f62009-05-14 15:44:42 -07001504 * View flag indicating whether this view was invalidated (fully or partially.)
1505 *
1506 * @hide
1507 */
1508 static final int DIRTY = 0x00200000;
1509
1510 /**
1511 * View flag indicating whether this view was invalidated by an opaque
1512 * invalidate request.
1513 *
1514 * @hide
1515 */
1516 static final int DIRTY_OPAQUE = 0x00400000;
1517
1518 /**
1519 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1520 *
1521 * @hide
1522 */
1523 static final int DIRTY_MASK = 0x00600000;
1524
1525 /**
Romain Guy8f1344f52009-05-15 16:03:59 -07001526 * Indicates whether the background is opaque.
1527 *
1528 * @hide
1529 */
1530 static final int OPAQUE_BACKGROUND = 0x00800000;
1531
1532 /**
1533 * Indicates whether the scrollbars are opaque.
1534 *
1535 * @hide
1536 */
1537 static final int OPAQUE_SCROLLBARS = 0x01000000;
1538
1539 /**
1540 * Indicates whether the view is opaque.
1541 *
1542 * @hide
1543 */
1544 static final int OPAQUE_MASK = 0x01800000;
Adam Powelle14579b2009-12-16 18:39:52 -08001545
1546 /**
1547 * Indicates a prepressed state;
1548 * the short time between ACTION_DOWN and recognizing
1549 * a 'real' press. Prepressed is used to recognize quick taps
1550 * even when they are shorter than ViewConfiguration.getTapTimeout().
1551 *
1552 * @hide
1553 */
1554 private static final int PREPRESSED = 0x02000000;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001555
1556 /**
Romain Guy8afa5152010-02-26 11:56:30 -08001557 * Indicates whether the view is temporarily detached.
1558 *
1559 * @hide
1560 */
1561 static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
Adam Powell8568c3a2010-04-19 14:26:11 -07001562
1563 /**
1564 * Indicates that we should awaken scroll bars once attached
1565 *
1566 * @hide
1567 */
1568 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
Romain Guy8f1344f52009-05-15 16:03:59 -07001569
1570 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001571 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1572 * for transform operations
1573 *
1574 * @hide
1575 */
1576 private static final int PIVOT_EXPLICITLY_SET = 0x10000000;
1577
1578 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 * The parent this view is attached to.
1580 * {@hide}
1581 *
1582 * @see #getParent()
1583 */
1584 protected ViewParent mParent;
1585
1586 /**
1587 * {@hide}
1588 */
1589 AttachInfo mAttachInfo;
1590
1591 /**
1592 * {@hide}
1593 */
Romain Guy809a7f62009-05-14 15:44:42 -07001594 @ViewDebug.ExportedProperty(flagMapping = {
1595 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1596 name = "FORCE_LAYOUT"),
1597 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1598 name = "LAYOUT_REQUIRED"),
1599 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001600 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001601 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1602 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1603 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1604 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1605 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 int mPrivateFlags;
1607
1608 /**
1609 * Count of how many windows this view has been attached to.
1610 */
1611 int mWindowAttachCount;
1612
1613 /**
1614 * The layout parameters associated with this view and used by the parent
1615 * {@link android.view.ViewGroup} to determine how this view should be
1616 * laid out.
1617 * {@hide}
1618 */
1619 protected ViewGroup.LayoutParams mLayoutParams;
1620
1621 /**
1622 * The view flags hold various views states.
1623 * {@hide}
1624 */
1625 @ViewDebug.ExportedProperty
1626 int mViewFlags;
1627
1628 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001629 * The transform matrix for the View. This transform is calculated internally
1630 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1631 * is used by default. Do *not* use this variable directly; instead call
1632 * getMatrix(), which will automatically recalculate the matrix if necessary
1633 * to get the correct matrix based on the latest rotation and scale properties.
1634 */
1635 private final Matrix mMatrix = new Matrix();
1636
1637 /**
1638 * The transform matrix for the View. This transform is calculated internally
1639 * based on the rotation, scaleX, and scaleY properties. The identity matrix
1640 * is used by default. Do *not* use this variable directly; instead call
1641 * getMatrix(), which will automatically recalculate the matrix if necessary
1642 * to get the correct matrix based on the latest rotation and scale properties.
1643 */
1644 private Matrix mInverseMatrix;
1645
1646 /**
1647 * An internal variable that tracks whether we need to recalculate the
1648 * transform matrix, based on whether the rotation or scaleX/Y properties
1649 * have changed since the matrix was last calculated.
1650 */
1651 private boolean mMatrixDirty = false;
1652
1653 /**
1654 * An internal variable that tracks whether we need to recalculate the
1655 * transform matrix, based on whether the rotation or scaleX/Y properties
1656 * have changed since the matrix was last calculated.
1657 */
1658 private boolean mInverseMatrixDirty = true;
1659
1660 /**
1661 * A variable that tracks whether we need to recalculate the
1662 * transform matrix, based on whether the rotation or scaleX/Y properties
1663 * have changed since the matrix was last calculated. This variable
1664 * is only valid after a call to getMatrix().
1665 */
Romain Guy33e72ae2010-07-17 12:40:29 -07001666 private boolean mMatrixIsIdentity = true;
Chet Haasec3aa3612010-06-17 08:50:37 -07001667
1668 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07001669 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1670 */
1671 private Camera mCamera = null;
1672
1673 /**
1674 * This matrix is used when computing the matrix for 3D rotations.
1675 */
1676 private Matrix matrix3D = null;
1677
1678 /**
1679 * These prev values are used to recalculate a centered pivot point when necessary. The
1680 * pivot point is only used in matrix operations (when rotation, scale, or translation are
1681 * set), so thes values are only used then as well.
1682 */
1683 private int mPrevWidth = -1;
1684 private int mPrevHeight = -1;
1685
1686 /**
1687 * Convenience value to check for float values that are close enough to zero to be considered
1688 * zero.
1689 */
Romain Guy2542d192010-08-18 11:47:12 -07001690 private static final float NONZERO_EPSILON = .001f;
Chet Haasefd2b0022010-08-06 13:08:56 -07001691
1692 /**
1693 * The degrees rotation around the vertical axis through the pivot point.
1694 */
1695 @ViewDebug.ExportedProperty
1696 private float mRotationY = 0f;
1697
1698 /**
1699 * The degrees rotation around the horizontal axis through the pivot point.
1700 */
1701 @ViewDebug.ExportedProperty
1702 private float mRotationX = 0f;
1703
1704 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001705 * The degrees rotation around the pivot point.
1706 */
1707 @ViewDebug.ExportedProperty
1708 private float mRotation = 0f;
1709
1710 /**
Chet Haasedf030d22010-07-30 17:22:38 -07001711 * The amount of translation of the object away from its left property (post-layout).
1712 */
1713 @ViewDebug.ExportedProperty
1714 private float mTranslationX = 0f;
1715
1716 /**
1717 * The amount of translation of the object away from its top property (post-layout).
1718 */
1719 @ViewDebug.ExportedProperty
1720 private float mTranslationY = 0f;
1721
1722 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07001723 * The amount of scale in the x direction around the pivot point. A
1724 * value of 1 means no scaling is applied.
1725 */
1726 @ViewDebug.ExportedProperty
1727 private float mScaleX = 1f;
1728
1729 /**
1730 * The amount of scale in the y direction around the pivot point. A
1731 * value of 1 means no scaling is applied.
1732 */
1733 @ViewDebug.ExportedProperty
1734 private float mScaleY = 1f;
1735
1736 /**
1737 * The amount of scale in the x direction around the pivot point. A
1738 * value of 1 means no scaling is applied.
1739 */
1740 @ViewDebug.ExportedProperty
1741 private float mPivotX = 0f;
1742
1743 /**
1744 * The amount of scale in the y direction around the pivot point. A
1745 * value of 1 means no scaling is applied.
1746 */
1747 @ViewDebug.ExportedProperty
1748 private float mPivotY = 0f;
1749
1750 /**
1751 * The opacity of the View. This is a value from 0 to 1, where 0 means
1752 * completely transparent and 1 means completely opaque.
1753 */
1754 @ViewDebug.ExportedProperty
1755 private float mAlpha = 1f;
1756
1757 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 * The distance in pixels from the left edge of this view's parent
1759 * to the left edge of this view.
1760 * {@hide}
1761 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001762 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 protected int mLeft;
1764 /**
1765 * The distance in pixels from the left edge of this view's parent
1766 * to the right edge of this view.
1767 * {@hide}
1768 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001769 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 protected int mRight;
1771 /**
1772 * The distance in pixels from the top edge of this view's parent
1773 * to the top edge of this view.
1774 * {@hide}
1775 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001776 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 protected int mTop;
1778 /**
1779 * The distance in pixels from the top edge of this view's parent
1780 * to the bottom edge of this view.
1781 * {@hide}
1782 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001783 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 protected int mBottom;
1785
1786 /**
1787 * The offset, in pixels, by which the content of this view is scrolled
1788 * horizontally.
1789 * {@hide}
1790 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001791 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 protected int mScrollX;
1793 /**
1794 * The offset, in pixels, by which the content of this view is scrolled
1795 * vertically.
1796 * {@hide}
1797 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001798 @ViewDebug.ExportedProperty(category = "scrolling")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 protected int mScrollY;
1800
1801 /**
1802 * The left padding in pixels, that is the distance in pixels between the
1803 * left edge of this view and the left edge of its content.
1804 * {@hide}
1805 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001806 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 protected int mPaddingLeft;
1808 /**
1809 * The right padding in pixels, that is the distance in pixels between the
1810 * right edge of this view and the right edge of its content.
1811 * {@hide}
1812 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001813 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 protected int mPaddingRight;
1815 /**
1816 * The top padding in pixels, that is the distance in pixels between the
1817 * top edge of this view and the top edge of its content.
1818 * {@hide}
1819 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001820 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 protected int mPaddingTop;
1822 /**
1823 * The bottom padding in pixels, that is the distance in pixels between the
1824 * bottom edge of this view and the bottom edge of its content.
1825 * {@hide}
1826 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001827 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 protected int mPaddingBottom;
1829
1830 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001831 * Briefly describes the view and is primarily used for accessibility support.
1832 */
1833 private CharSequence mContentDescription;
1834
1835 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 * Cache the paddingRight set by the user to append to the scrollbar's size.
1837 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001838 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 int mUserPaddingRight;
1840
1841 /**
1842 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1843 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001844 @ViewDebug.ExportedProperty(category = "padding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 int mUserPaddingBottom;
1846
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001847 /**
1848 * @hide
1849 */
1850 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1851 /**
1852 * @hide
1853 */
1854 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855
1856 private Resources mResources = null;
1857
1858 private Drawable mBGDrawable;
1859
1860 private int mBackgroundResource;
1861 private boolean mBackgroundSizeChanged;
1862
1863 /**
1864 * Listener used to dispatch focus change events.
1865 * This field should be made private, so it is hidden from the SDK.
1866 * {@hide}
1867 */
1868 protected OnFocusChangeListener mOnFocusChangeListener;
1869
1870 /**
Chet Haase21cd1382010-09-01 17:42:29 -07001871 * Listeners for layout change events.
1872 */
1873 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
1874
1875 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 * Listener used to dispatch click events.
1877 * This field should be made private, so it is hidden from the SDK.
1878 * {@hide}
1879 */
1880 protected OnClickListener mOnClickListener;
1881
1882 /**
1883 * Listener used to dispatch long click events.
1884 * This field should be made private, so it is hidden from the SDK.
1885 * {@hide}
1886 */
1887 protected OnLongClickListener mOnLongClickListener;
1888
1889 /**
1890 * Listener used to build the context menu.
1891 * This field should be made private, so it is hidden from the SDK.
1892 * {@hide}
1893 */
1894 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
1895
1896 private OnKeyListener mOnKeyListener;
1897
1898 private OnTouchListener mOnTouchListener;
1899
1900 /**
1901 * The application environment this view lives in.
1902 * This field should be made private, so it is hidden from the SDK.
1903 * {@hide}
1904 */
1905 protected Context mContext;
1906
1907 private ScrollabilityCache mScrollCache;
1908
1909 private int[] mDrawableState = null;
1910
Romain Guy02890fd2010-08-06 17:58:44 -07001911 private Bitmap mDrawingCache;
1912 private Bitmap mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913
1914 /**
1915 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
1916 * the user may specify which view to go to next.
1917 */
1918 private int mNextFocusLeftId = View.NO_ID;
1919
1920 /**
1921 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
1922 * the user may specify which view to go to next.
1923 */
1924 private int mNextFocusRightId = View.NO_ID;
1925
1926 /**
1927 * When this view has focus and the next focus is {@link #FOCUS_UP},
1928 * the user may specify which view to go to next.
1929 */
1930 private int mNextFocusUpId = View.NO_ID;
1931
1932 /**
1933 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
1934 * the user may specify which view to go to next.
1935 */
1936 private int mNextFocusDownId = View.NO_ID;
1937
1938 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08001939 private CheckForTap mPendingCheckForTap = null;
Adam Powella35d7682010-03-12 14:48:13 -08001940 private PerformClick mPerformClick;
Adam Powelle14579b2009-12-16 18:39:52 -08001941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 private UnsetPressedState mUnsetPressedState;
1943
1944 /**
1945 * Whether the long press's action has been invoked. The tap's action is invoked on the
1946 * up event while a long press is invoked as soon as the long press duration is reached, so
1947 * a long press could be performed before the tap is checked, in which case the tap's action
1948 * should not be invoked.
1949 */
1950 private boolean mHasPerformedLongPress;
1951
1952 /**
1953 * The minimum height of the view. We'll try our best to have the height
1954 * of this view to at least this amount.
1955 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001956 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 private int mMinHeight;
1958
1959 /**
1960 * The minimum width of the view. We'll try our best to have the width
1961 * of this view to at least this amount.
1962 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001963 @ViewDebug.ExportedProperty(category = "measurement")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 private int mMinWidth;
1965
1966 /**
1967 * The delegate to handle touch events that are physically in this view
1968 * but should be handled by another view.
1969 */
1970 private TouchDelegate mTouchDelegate = null;
1971
1972 /**
1973 * Solid color to use as a background when creating the drawing cache. Enables
1974 * the cache to use 16 bit bitmaps instead of 32 bit.
1975 */
1976 private int mDrawingCacheBackgroundColor = 0;
1977
1978 /**
1979 * Special tree observer used when mAttachInfo is null.
1980 */
1981 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08001982
1983 /**
1984 * Cache the touch slop from the context that created the view.
1985 */
1986 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 /**
1989 * Simple constructor to use when creating a view from code.
1990 *
1991 * @param context The Context the view is running in, through which it can
1992 * access the current theme, resources, etc.
1993 */
1994 public View(Context context) {
1995 mContext = context;
1996 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07001997 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
Adam Powelle14579b2009-12-16 18:39:52 -08001998 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 }
2000
2001 /**
2002 * Constructor that is called when inflating a view from XML. This is called
2003 * when a view is being constructed from an XML file, supplying attributes
2004 * that were specified in the XML file. This version uses a default style of
2005 * 0, so the only attribute values applied are those in the Context's Theme
2006 * and the given AttributeSet.
2007 *
2008 * <p>
2009 * The method onFinishInflate() will be called after all children have been
2010 * added.
2011 *
2012 * @param context The Context the view is running in, through which it can
2013 * access the current theme, resources, etc.
2014 * @param attrs The attributes of the XML tag that is inflating the view.
2015 * @see #View(Context, AttributeSet, int)
2016 */
2017 public View(Context context, AttributeSet attrs) {
2018 this(context, attrs, 0);
2019 }
2020
2021 /**
2022 * Perform inflation from XML and apply a class-specific base style. This
2023 * constructor of View allows subclasses to use their own base style when
2024 * they are inflating. For example, a Button class's constructor would call
2025 * this version of the super class constructor and supply
2026 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2027 * the theme's button style to modify all of the base view attributes (in
2028 * particular its background) as well as the Button class's attributes.
2029 *
2030 * @param context The Context the view is running in, through which it can
2031 * access the current theme, resources, etc.
2032 * @param attrs The attributes of the XML tag that is inflating the view.
2033 * @param defStyle The default style to apply to this view. If 0, no style
2034 * will be applied (beyond what is included in the theme). This may
2035 * either be an attribute resource, whose value will be retrieved
2036 * from the current theme, or an explicit style resource.
2037 * @see #View(Context, AttributeSet)
2038 */
2039 public View(Context context, AttributeSet attrs, int defStyle) {
2040 this(context);
2041
2042 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2043 defStyle, 0);
2044
2045 Drawable background = null;
2046
2047 int leftPadding = -1;
2048 int topPadding = -1;
2049 int rightPadding = -1;
2050 int bottomPadding = -1;
2051
2052 int padding = -1;
2053
2054 int viewFlagValues = 0;
2055 int viewFlagMasks = 0;
2056
2057 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 int x = 0;
2060 int y = 0;
2061
2062 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2063
2064 final int N = a.getIndexCount();
2065 for (int i = 0; i < N; i++) {
2066 int attr = a.getIndex(i);
2067 switch (attr) {
2068 case com.android.internal.R.styleable.View_background:
2069 background = a.getDrawable(attr);
2070 break;
2071 case com.android.internal.R.styleable.View_padding:
2072 padding = a.getDimensionPixelSize(attr, -1);
2073 break;
2074 case com.android.internal.R.styleable.View_paddingLeft:
2075 leftPadding = a.getDimensionPixelSize(attr, -1);
2076 break;
2077 case com.android.internal.R.styleable.View_paddingTop:
2078 topPadding = a.getDimensionPixelSize(attr, -1);
2079 break;
2080 case com.android.internal.R.styleable.View_paddingRight:
2081 rightPadding = a.getDimensionPixelSize(attr, -1);
2082 break;
2083 case com.android.internal.R.styleable.View_paddingBottom:
2084 bottomPadding = a.getDimensionPixelSize(attr, -1);
2085 break;
2086 case com.android.internal.R.styleable.View_scrollX:
2087 x = a.getDimensionPixelOffset(attr, 0);
2088 break;
2089 case com.android.internal.R.styleable.View_scrollY:
2090 y = a.getDimensionPixelOffset(attr, 0);
2091 break;
2092 case com.android.internal.R.styleable.View_id:
2093 mID = a.getResourceId(attr, NO_ID);
2094 break;
2095 case com.android.internal.R.styleable.View_tag:
2096 mTag = a.getText(attr);
2097 break;
2098 case com.android.internal.R.styleable.View_fitsSystemWindows:
2099 if (a.getBoolean(attr, false)) {
2100 viewFlagValues |= FITS_SYSTEM_WINDOWS;
2101 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2102 }
2103 break;
2104 case com.android.internal.R.styleable.View_focusable:
2105 if (a.getBoolean(attr, false)) {
2106 viewFlagValues |= FOCUSABLE;
2107 viewFlagMasks |= FOCUSABLE_MASK;
2108 }
2109 break;
2110 case com.android.internal.R.styleable.View_focusableInTouchMode:
2111 if (a.getBoolean(attr, false)) {
2112 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2113 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2114 }
2115 break;
2116 case com.android.internal.R.styleable.View_clickable:
2117 if (a.getBoolean(attr, false)) {
2118 viewFlagValues |= CLICKABLE;
2119 viewFlagMasks |= CLICKABLE;
2120 }
2121 break;
2122 case com.android.internal.R.styleable.View_longClickable:
2123 if (a.getBoolean(attr, false)) {
2124 viewFlagValues |= LONG_CLICKABLE;
2125 viewFlagMasks |= LONG_CLICKABLE;
2126 }
2127 break;
2128 case com.android.internal.R.styleable.View_saveEnabled:
2129 if (!a.getBoolean(attr, true)) {
2130 viewFlagValues |= SAVE_DISABLED;
2131 viewFlagMasks |= SAVE_DISABLED_MASK;
2132 }
2133 break;
2134 case com.android.internal.R.styleable.View_duplicateParentState:
2135 if (a.getBoolean(attr, false)) {
2136 viewFlagValues |= DUPLICATE_PARENT_STATE;
2137 viewFlagMasks |= DUPLICATE_PARENT_STATE;
2138 }
2139 break;
2140 case com.android.internal.R.styleable.View_visibility:
2141 final int visibility = a.getInt(attr, 0);
2142 if (visibility != 0) {
2143 viewFlagValues |= VISIBILITY_FLAGS[visibility];
2144 viewFlagMasks |= VISIBILITY_MASK;
2145 }
2146 break;
2147 case com.android.internal.R.styleable.View_drawingCacheQuality:
2148 final int cacheQuality = a.getInt(attr, 0);
2149 if (cacheQuality != 0) {
2150 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2151 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2152 }
2153 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07002154 case com.android.internal.R.styleable.View_contentDescription:
2155 mContentDescription = a.getString(attr);
2156 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 case com.android.internal.R.styleable.View_soundEffectsEnabled:
2158 if (!a.getBoolean(attr, true)) {
2159 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2160 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2161 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002162 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2164 if (!a.getBoolean(attr, true)) {
2165 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2166 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2167 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07002168 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 case R.styleable.View_scrollbars:
2170 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2171 if (scrollbars != SCROLLBARS_NONE) {
2172 viewFlagValues |= scrollbars;
2173 viewFlagMasks |= SCROLLBARS_MASK;
2174 initializeScrollbars(a);
2175 }
2176 break;
2177 case R.styleable.View_fadingEdge:
2178 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2179 if (fadingEdge != FADING_EDGE_NONE) {
2180 viewFlagValues |= fadingEdge;
2181 viewFlagMasks |= FADING_EDGE_MASK;
2182 initializeFadingEdge(a);
2183 }
2184 break;
2185 case R.styleable.View_scrollbarStyle:
2186 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2187 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2188 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2189 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2190 }
2191 break;
2192 case R.styleable.View_isScrollContainer:
2193 setScrollContainer = true;
2194 if (a.getBoolean(attr, false)) {
2195 setScrollContainer(true);
2196 }
2197 break;
2198 case com.android.internal.R.styleable.View_keepScreenOn:
2199 if (a.getBoolean(attr, false)) {
2200 viewFlagValues |= KEEP_SCREEN_ON;
2201 viewFlagMasks |= KEEP_SCREEN_ON;
2202 }
2203 break;
Jeff Brown85a31762010-09-01 17:01:00 -07002204 case R.styleable.View_filterTouchesWhenObscured:
2205 if (a.getBoolean(attr, false)) {
2206 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2207 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2208 }
2209 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 case R.styleable.View_nextFocusLeft:
2211 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2212 break;
2213 case R.styleable.View_nextFocusRight:
2214 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2215 break;
2216 case R.styleable.View_nextFocusUp:
2217 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2218 break;
2219 case R.styleable.View_nextFocusDown:
2220 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2221 break;
2222 case R.styleable.View_minWidth:
2223 mMinWidth = a.getDimensionPixelSize(attr, 0);
2224 break;
2225 case R.styleable.View_minHeight:
2226 mMinHeight = a.getDimensionPixelSize(attr, 0);
2227 break;
Romain Guy9a817362009-05-01 10:57:14 -07002228 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002229 if (context.isRestricted()) {
2230 throw new IllegalStateException("The android:onClick attribute cannot "
2231 + "be used within a restricted context");
2232 }
2233
Romain Guy9a817362009-05-01 10:57:14 -07002234 final String handlerName = a.getString(attr);
2235 if (handlerName != null) {
2236 setOnClickListener(new OnClickListener() {
2237 private Method mHandler;
2238
2239 public void onClick(View v) {
2240 if (mHandler == null) {
2241 try {
2242 mHandler = getContext().getClass().getMethod(handlerName,
2243 View.class);
2244 } catch (NoSuchMethodException e) {
Joe Onorato42e14d72010-03-11 14:51:17 -08002245 int id = getId();
2246 String idText = id == NO_ID ? "" : " with id '"
2247 + getContext().getResources().getResourceEntryName(
2248 id) + "'";
Romain Guy9a817362009-05-01 10:57:14 -07002249 throw new IllegalStateException("Could not find a method " +
Joe Onorato42e14d72010-03-11 14:51:17 -08002250 handlerName + "(View) in the activity "
2251 + getContext().getClass() + " for onClick handler"
2252 + " on view " + View.this.getClass() + idText, e);
Romain Guy9a817362009-05-01 10:57:14 -07002253 }
2254 }
2255
2256 try {
2257 mHandler.invoke(getContext(), View.this);
2258 } catch (IllegalAccessException e) {
2259 throw new IllegalStateException("Could not execute non "
2260 + "public method of the activity", e);
2261 } catch (InvocationTargetException e) {
2262 throw new IllegalStateException("Could not execute "
2263 + "method of the activity", e);
2264 }
2265 }
2266 });
2267 }
2268 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 }
2270 }
2271
2272 if (background != null) {
2273 setBackgroundDrawable(background);
2274 }
2275
2276 if (padding >= 0) {
2277 leftPadding = padding;
2278 topPadding = padding;
2279 rightPadding = padding;
2280 bottomPadding = padding;
2281 }
2282
2283 // If the user specified the padding (either with android:padding or
2284 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2285 // use the default padding or the padding from the background drawable
2286 // (stored at this point in mPadding*)
2287 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2288 topPadding >= 0 ? topPadding : mPaddingTop,
2289 rightPadding >= 0 ? rightPadding : mPaddingRight,
2290 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2291
2292 if (viewFlagMasks != 0) {
2293 setFlags(viewFlagValues, viewFlagMasks);
2294 }
2295
2296 // Needs to be called after mViewFlags is set
2297 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2298 recomputePadding();
2299 }
2300
2301 if (x != 0 || y != 0) {
2302 scrollTo(x, y);
2303 }
2304
2305 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2306 setScrollContainer(true);
2307 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002308
2309 computeOpaqueFlags();
2310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 a.recycle();
2312 }
2313
2314 /**
2315 * Non-public constructor for use in testing
2316 */
2317 View() {
2318 }
2319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320 /**
2321 * <p>
2322 * Initializes the fading edges from a given set of styled attributes. This
2323 * method should be called by subclasses that need fading edges and when an
2324 * instance of these subclasses is created programmatically rather than
2325 * being inflated from XML. This method is automatically called when the XML
2326 * is inflated.
2327 * </p>
2328 *
2329 * @param a the styled attributes set to initialize the fading edges from
2330 */
2331 protected void initializeFadingEdge(TypedArray a) {
2332 initScrollCache();
2333
2334 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2335 R.styleable.View_fadingEdgeLength,
2336 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2337 }
2338
2339 /**
2340 * Returns the size of the vertical faded edges used to indicate that more
2341 * content in this view is visible.
2342 *
2343 * @return The size in pixels of the vertical faded edge or 0 if vertical
2344 * faded edges are not enabled for this view.
2345 * @attr ref android.R.styleable#View_fadingEdgeLength
2346 */
2347 public int getVerticalFadingEdgeLength() {
2348 if (isVerticalFadingEdgeEnabled()) {
2349 ScrollabilityCache cache = mScrollCache;
2350 if (cache != null) {
2351 return cache.fadingEdgeLength;
2352 }
2353 }
2354 return 0;
2355 }
2356
2357 /**
2358 * Set the size of the faded edge used to indicate that more content in this
2359 * view is available. Will not change whether the fading edge is enabled; use
2360 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2361 * to enable the fading edge for the vertical or horizontal fading edges.
2362 *
2363 * @param length The size in pixels of the faded edge used to indicate that more
2364 * content in this view is visible.
2365 */
2366 public void setFadingEdgeLength(int length) {
2367 initScrollCache();
2368 mScrollCache.fadingEdgeLength = length;
2369 }
2370
2371 /**
2372 * Returns the size of the horizontal faded edges used to indicate that more
2373 * content in this view is visible.
2374 *
2375 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2376 * faded edges are not enabled for this view.
2377 * @attr ref android.R.styleable#View_fadingEdgeLength
2378 */
2379 public int getHorizontalFadingEdgeLength() {
2380 if (isHorizontalFadingEdgeEnabled()) {
2381 ScrollabilityCache cache = mScrollCache;
2382 if (cache != null) {
2383 return cache.fadingEdgeLength;
2384 }
2385 }
2386 return 0;
2387 }
2388
2389 /**
2390 * Returns the width of the vertical scrollbar.
2391 *
2392 * @return The width in pixels of the vertical scrollbar or 0 if there
2393 * is no vertical scrollbar.
2394 */
2395 public int getVerticalScrollbarWidth() {
2396 ScrollabilityCache cache = mScrollCache;
2397 if (cache != null) {
2398 ScrollBarDrawable scrollBar = cache.scrollBar;
2399 if (scrollBar != null) {
2400 int size = scrollBar.getSize(true);
2401 if (size <= 0) {
2402 size = cache.scrollBarSize;
2403 }
2404 return size;
2405 }
2406 return 0;
2407 }
2408 return 0;
2409 }
2410
2411 /**
2412 * Returns the height of the horizontal scrollbar.
2413 *
2414 * @return The height in pixels of the horizontal scrollbar or 0 if
2415 * there is no horizontal scrollbar.
2416 */
2417 protected int getHorizontalScrollbarHeight() {
2418 ScrollabilityCache cache = mScrollCache;
2419 if (cache != null) {
2420 ScrollBarDrawable scrollBar = cache.scrollBar;
2421 if (scrollBar != null) {
2422 int size = scrollBar.getSize(false);
2423 if (size <= 0) {
2424 size = cache.scrollBarSize;
2425 }
2426 return size;
2427 }
2428 return 0;
2429 }
2430 return 0;
2431 }
2432
2433 /**
2434 * <p>
2435 * Initializes the scrollbars from a given set of styled attributes. This
2436 * method should be called by subclasses that need scrollbars and when an
2437 * instance of these subclasses is created programmatically rather than
2438 * being inflated from XML. This method is automatically called when the XML
2439 * is inflated.
2440 * </p>
2441 *
2442 * @param a the styled attributes set to initialize the scrollbars from
2443 */
2444 protected void initializeScrollbars(TypedArray a) {
2445 initScrollCache();
2446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002448
2449 if (scrollabilityCache.scrollBar == null) {
2450 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2451 }
2452
Romain Guy8bda2482010-03-02 11:42:11 -08002453 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454
Mike Cleronf116bf82009-09-27 19:14:12 -07002455 if (!fadeScrollbars) {
2456 scrollabilityCache.state = ScrollabilityCache.ON;
2457 }
2458 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2459
2460
2461 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2462 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2463 .getScrollBarFadeDuration());
2464 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2465 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2466 ViewConfiguration.getScrollDefaultDelay());
2467
2468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2470 com.android.internal.R.styleable.View_scrollbarSize,
2471 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2472
2473 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2474 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2475
2476 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2477 if (thumb != null) {
2478 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2479 }
2480
2481 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2482 false);
2483 if (alwaysDraw) {
2484 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2485 }
2486
2487 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2488 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2489
2490 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2491 if (thumb != null) {
2492 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2493 }
2494
2495 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2496 false);
2497 if (alwaysDraw) {
2498 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2499 }
2500
2501 // Re-apply user/background padding so that scrollbar(s) get added
2502 recomputePadding();
2503 }
2504
2505 /**
2506 * <p>
2507 * Initalizes the scrollability cache if necessary.
2508 * </p>
2509 */
2510 private void initScrollCache() {
2511 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002512 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 }
2514 }
2515
2516 /**
2517 * Register a callback to be invoked when focus of this view changed.
2518 *
2519 * @param l The callback that will run.
2520 */
2521 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2522 mOnFocusChangeListener = l;
2523 }
2524
2525 /**
Chet Haase21cd1382010-09-01 17:42:29 -07002526 * Add a listener that will be called when the bounds of the view change due to
2527 * layout processing.
2528 *
2529 * @param listener The listener that will be called when layout bounds change.
2530 */
2531 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2532 if (mOnLayoutChangeListeners == null) {
2533 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2534 }
2535 mOnLayoutChangeListeners.add(listener);
2536 }
2537
2538 /**
2539 * Remove a listener for layout changes.
2540 *
2541 * @param listener The listener for layout bounds change.
2542 */
2543 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2544 if (mOnLayoutChangeListeners == null) {
2545 return;
2546 }
2547 mOnLayoutChangeListeners.remove(listener);
2548 }
2549
2550 /**
2551 * Gets the current list of listeners for layout changes.
2552 * @return
2553 */
2554 public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2555 return mOnLayoutChangeListeners;
2556 }
2557
2558 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 * Returns the focus-change callback registered for this view.
2560 *
2561 * @return The callback, or null if one is not registered.
2562 */
2563 public OnFocusChangeListener getOnFocusChangeListener() {
2564 return mOnFocusChangeListener;
2565 }
2566
2567 /**
2568 * Register a callback to be invoked when this view is clicked. If this view is not
2569 * clickable, it becomes clickable.
2570 *
2571 * @param l The callback that will run
2572 *
2573 * @see #setClickable(boolean)
2574 */
2575 public void setOnClickListener(OnClickListener l) {
2576 if (!isClickable()) {
2577 setClickable(true);
2578 }
2579 mOnClickListener = l;
2580 }
2581
2582 /**
2583 * Register a callback to be invoked when this view is clicked and held. If this view is not
2584 * long clickable, it becomes long clickable.
2585 *
2586 * @param l The callback that will run
2587 *
2588 * @see #setLongClickable(boolean)
2589 */
2590 public void setOnLongClickListener(OnLongClickListener l) {
2591 if (!isLongClickable()) {
2592 setLongClickable(true);
2593 }
2594 mOnLongClickListener = l;
2595 }
2596
2597 /**
2598 * Register a callback to be invoked when the context menu for this view is
2599 * being built. If this view is not long clickable, it becomes long clickable.
2600 *
2601 * @param l The callback that will run
2602 *
2603 */
2604 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2605 if (!isLongClickable()) {
2606 setLongClickable(true);
2607 }
2608 mOnCreateContextMenuListener = l;
2609 }
2610
2611 /**
2612 * Call this view's OnClickListener, if it is defined.
2613 *
2614 * @return True there was an assigned OnClickListener that was called, false
2615 * otherwise is returned.
2616 */
2617 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002618 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 if (mOnClickListener != null) {
2621 playSoundEffect(SoundEffectConstants.CLICK);
2622 mOnClickListener.onClick(this);
2623 return true;
2624 }
2625
2626 return false;
2627 }
2628
2629 /**
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002630 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2631 * OnLongClickListener did not consume the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07002633 * @return True if one of the above receivers consumed the event, false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 */
2635 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002636 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 boolean handled = false;
2639 if (mOnLongClickListener != null) {
2640 handled = mOnLongClickListener.onLongClick(View.this);
2641 }
2642 if (!handled) {
2643 handled = showContextMenu();
2644 }
2645 if (handled) {
2646 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2647 }
2648 return handled;
2649 }
2650
2651 /**
2652 * Bring up the context menu for this view.
2653 *
2654 * @return Whether a context menu was displayed.
2655 */
2656 public boolean showContextMenu() {
2657 return getParent().showContextMenuForChild(this);
2658 }
2659
2660 /**
Adam Powell6e346362010-07-23 10:18:23 -07002661 * Start an action mode.
2662 *
2663 * @param callback Callback that will control the lifecycle of the action mode
2664 * @return The new action mode if it is started, null otherwise
2665 *
2666 * @see ActionMode
2667 */
2668 public ActionMode startActionMode(ActionMode.Callback callback) {
2669 return getParent().startActionModeForChild(this, callback);
2670 }
2671
2672 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 * Register a callback to be invoked when a key is pressed in this view.
2674 * @param l the key listener to attach to this view
2675 */
2676 public void setOnKeyListener(OnKeyListener l) {
2677 mOnKeyListener = l;
2678 }
2679
2680 /**
2681 * Register a callback to be invoked when a touch event is sent to this view.
2682 * @param l the touch listener to attach to this view
2683 */
2684 public void setOnTouchListener(OnTouchListener l) {
2685 mOnTouchListener = l;
2686 }
2687
2688 /**
2689 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2690 *
2691 * Note: this does not check whether this {@link View} should get focus, it just
2692 * gives it focus no matter what. It should only be called internally by framework
2693 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2694 *
2695 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2696 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2697 * focus moved when requestFocus() is called. It may not always
2698 * apply, in which case use the default View.FOCUS_DOWN.
2699 * @param previouslyFocusedRect The rectangle of the view that had focus
2700 * prior in this View's coordinate system.
2701 */
2702 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2703 if (DBG) {
2704 System.out.println(this + " requestFocus()");
2705 }
2706
2707 if ((mPrivateFlags & FOCUSED) == 0) {
2708 mPrivateFlags |= FOCUSED;
2709
2710 if (mParent != null) {
2711 mParent.requestChildFocus(this, this);
2712 }
2713
2714 onFocusChanged(true, direction, previouslyFocusedRect);
2715 refreshDrawableState();
2716 }
2717 }
2718
2719 /**
2720 * Request that a rectangle of this view be visible on the screen,
2721 * scrolling if necessary just enough.
2722 *
2723 * <p>A View should call this if it maintains some notion of which part
2724 * of its content is interesting. For example, a text editing view
2725 * should call this when its cursor moves.
2726 *
2727 * @param rectangle The rectangle.
2728 * @return Whether any parent scrolled.
2729 */
2730 public boolean requestRectangleOnScreen(Rect rectangle) {
2731 return requestRectangleOnScreen(rectangle, false);
2732 }
2733
2734 /**
2735 * Request that a rectangle of this view be visible on the screen,
2736 * scrolling if necessary just enough.
2737 *
2738 * <p>A View should call this if it maintains some notion of which part
2739 * of its content is interesting. For example, a text editing view
2740 * should call this when its cursor moves.
2741 *
2742 * <p>When <code>immediate</code> is set to true, scrolling will not be
2743 * animated.
2744 *
2745 * @param rectangle The rectangle.
2746 * @param immediate True to forbid animated scrolling, false otherwise
2747 * @return Whether any parent scrolled.
2748 */
2749 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
2750 View child = this;
2751 ViewParent parent = mParent;
2752 boolean scrolled = false;
2753 while (parent != null) {
2754 scrolled |= parent.requestChildRectangleOnScreen(child,
2755 rectangle, immediate);
2756
2757 // offset rect so next call has the rectangle in the
2758 // coordinate system of its direct child.
2759 rectangle.offset(child.getLeft(), child.getTop());
2760 rectangle.offset(-child.getScrollX(), -child.getScrollY());
2761
2762 if (!(parent instanceof View)) {
2763 break;
2764 }
Romain Guy8506ab42009-06-11 17:35:47 -07002765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 child = (View) parent;
2767 parent = child.getParent();
2768 }
2769 return scrolled;
2770 }
2771
2772 /**
2773 * Called when this view wants to give up focus. This will cause
2774 * {@link #onFocusChanged} to be called.
2775 */
2776 public void clearFocus() {
2777 if (DBG) {
2778 System.out.println(this + " clearFocus()");
2779 }
2780
2781 if ((mPrivateFlags & FOCUSED) != 0) {
2782 mPrivateFlags &= ~FOCUSED;
2783
2784 if (mParent != null) {
2785 mParent.clearChildFocus(this);
2786 }
2787
2788 onFocusChanged(false, 0, null);
2789 refreshDrawableState();
2790 }
2791 }
2792
2793 /**
2794 * Called to clear the focus of a view that is about to be removed.
2795 * Doesn't call clearChildFocus, which prevents this view from taking
2796 * focus again before it has been removed from the parent
2797 */
2798 void clearFocusForRemoval() {
2799 if ((mPrivateFlags & FOCUSED) != 0) {
2800 mPrivateFlags &= ~FOCUSED;
2801
2802 onFocusChanged(false, 0, null);
2803 refreshDrawableState();
2804 }
2805 }
2806
2807 /**
2808 * Called internally by the view system when a new view is getting focus.
2809 * This is what clears the old focus.
2810 */
2811 void unFocus() {
2812 if (DBG) {
2813 System.out.println(this + " unFocus()");
2814 }
2815
2816 if ((mPrivateFlags & FOCUSED) != 0) {
2817 mPrivateFlags &= ~FOCUSED;
2818
2819 onFocusChanged(false, 0, null);
2820 refreshDrawableState();
2821 }
2822 }
2823
2824 /**
2825 * Returns true if this view has focus iteself, or is the ancestor of the
2826 * view that has focus.
2827 *
2828 * @return True if this view has or contains focus, false otherwise.
2829 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07002830 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 public boolean hasFocus() {
2832 return (mPrivateFlags & FOCUSED) != 0;
2833 }
2834
2835 /**
2836 * Returns true if this view is focusable or if it contains a reachable View
2837 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
2838 * is a View whose parents do not block descendants focus.
2839 *
2840 * Only {@link #VISIBLE} views are considered focusable.
2841 *
2842 * @return True if the view is focusable or if the view contains a focusable
2843 * View, false otherwise.
2844 *
2845 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
2846 */
2847 public boolean hasFocusable() {
2848 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
2849 }
2850
2851 /**
2852 * Called by the view system when the focus state of this view changes.
2853 * When the focus change event is caused by directional navigation, direction
2854 * and previouslyFocusedRect provide insight into where the focus is coming from.
2855 * When overriding, be sure to call up through to the super class so that
2856 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07002857 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 * @param gainFocus True if the View has focus; false otherwise.
2859 * @param direction The direction focus has moved when requestFocus()
2860 * is called to give this view focus. Values are
Romain Guyea4823c2009-12-08 15:03:39 -08002861 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT} or
2862 * {@link #FOCUS_RIGHT}. It may not always apply, in which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 * case use the default.
2864 * @param previouslyFocusedRect The rectangle, in this view's coordinate
2865 * system, of the previously focused view. If applicable, this will be
2866 * passed in as finer grained information about where the focus is coming
2867 * from (in addition to direction). Will be <code>null</code> otherwise.
2868 */
2869 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07002870 if (gainFocus) {
2871 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2872 }
2873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 InputMethodManager imm = InputMethodManager.peekInstance();
2875 if (!gainFocus) {
2876 if (isPressed()) {
2877 setPressed(false);
2878 }
2879 if (imm != null && mAttachInfo != null
2880 && mAttachInfo.mHasWindowFocus) {
2881 imm.focusOut(this);
2882 }
Romain Guya2431d02009-04-30 16:30:00 -07002883 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 } else if (imm != null && mAttachInfo != null
2885 && mAttachInfo.mHasWindowFocus) {
2886 imm.focusIn(this);
2887 }
Romain Guy8506ab42009-06-11 17:35:47 -07002888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 invalidate();
2890 if (mOnFocusChangeListener != null) {
2891 mOnFocusChangeListener.onFocusChange(this, gainFocus);
2892 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002893
2894 if (mAttachInfo != null) {
2895 mAttachInfo.mKeyDispatchState.reset(this);
2896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 }
2898
2899 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002900 * {@inheritDoc}
2901 */
2902 public void sendAccessibilityEvent(int eventType) {
2903 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
2904 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
2905 }
2906 }
2907
2908 /**
2909 * {@inheritDoc}
2910 */
2911 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
2912 event.setClassName(getClass().getName());
2913 event.setPackageName(getContext().getPackageName());
2914 event.setEnabled(isEnabled());
2915 event.setContentDescription(mContentDescription);
2916
2917 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
2918 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
2919 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
2920 event.setItemCount(focusablesTempList.size());
2921 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
2922 focusablesTempList.clear();
2923 }
2924
2925 dispatchPopulateAccessibilityEvent(event);
2926
2927 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
2928 }
2929
2930 /**
2931 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
2932 * to be populated.
2933 *
2934 * @param event The event.
2935 *
2936 * @return True if the event population was completed.
2937 */
2938 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2939 return false;
2940 }
2941
2942 /**
2943 * Gets the {@link View} description. It briefly describes the view and is
2944 * primarily used for accessibility support. Set this property to enable
2945 * better accessibility support for your application. This is especially
2946 * true for views that do not have textual representation (For example,
2947 * ImageButton).
2948 *
2949 * @return The content descriptiopn.
2950 *
2951 * @attr ref android.R.styleable#View_contentDescription
2952 */
2953 public CharSequence getContentDescription() {
2954 return mContentDescription;
2955 }
2956
2957 /**
2958 * Sets the {@link View} description. It briefly describes the view and is
2959 * primarily used for accessibility support. Set this property to enable
2960 * better accessibility support for your application. This is especially
2961 * true for views that do not have textual representation (For example,
2962 * ImageButton).
2963 *
2964 * @param contentDescription The content description.
2965 *
2966 * @attr ref android.R.styleable#View_contentDescription
2967 */
2968 public void setContentDescription(CharSequence contentDescription) {
2969 mContentDescription = contentDescription;
2970 }
2971
2972 /**
Romain Guya2431d02009-04-30 16:30:00 -07002973 * Invoked whenever this view loses focus, either by losing window focus or by losing
2974 * focus within its window. This method can be used to clear any state tied to the
2975 * focus. For instance, if a button is held pressed with the trackball and the window
2976 * loses focus, this method can be used to cancel the press.
2977 *
2978 * Subclasses of View overriding this method should always call super.onFocusLost().
2979 *
2980 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07002981 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07002982 *
2983 * @hide pending API council approval
2984 */
2985 protected void onFocusLost() {
2986 resetPressedState();
2987 }
2988
2989 private void resetPressedState() {
2990 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
2991 return;
2992 }
2993
2994 if (isPressed()) {
2995 setPressed(false);
2996
2997 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05002998 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07002999 }
3000 }
3001 }
3002
3003 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 * Returns true if this view has focus
3005 *
3006 * @return True if this view has focus, false otherwise.
3007 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003008 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 public boolean isFocused() {
3010 return (mPrivateFlags & FOCUSED) != 0;
3011 }
3012
3013 /**
3014 * Find the view in the hierarchy rooted at this view that currently has
3015 * focus.
3016 *
3017 * @return The view that currently has focus, or null if no focused view can
3018 * be found.
3019 */
3020 public View findFocus() {
3021 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3022 }
3023
3024 /**
3025 * Change whether this view is one of the set of scrollable containers in
3026 * its window. This will be used to determine whether the window can
3027 * resize or must pan when a soft input area is open -- scrollable
3028 * containers allow the window to use resize mode since the container
3029 * will appropriately shrink.
3030 */
3031 public void setScrollContainer(boolean isScrollContainer) {
3032 if (isScrollContainer) {
3033 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3034 mAttachInfo.mScrollContainers.add(this);
3035 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3036 }
3037 mPrivateFlags |= SCROLL_CONTAINER;
3038 } else {
3039 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3040 mAttachInfo.mScrollContainers.remove(this);
3041 }
3042 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3043 }
3044 }
3045
3046 /**
3047 * Returns the quality of the drawing cache.
3048 *
3049 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3050 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3051 *
3052 * @see #setDrawingCacheQuality(int)
3053 * @see #setDrawingCacheEnabled(boolean)
3054 * @see #isDrawingCacheEnabled()
3055 *
3056 * @attr ref android.R.styleable#View_drawingCacheQuality
3057 */
3058 public int getDrawingCacheQuality() {
3059 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3060 }
3061
3062 /**
3063 * Set the drawing cache quality of this view. This value is used only when the
3064 * drawing cache is enabled
3065 *
3066 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3067 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3068 *
3069 * @see #getDrawingCacheQuality()
3070 * @see #setDrawingCacheEnabled(boolean)
3071 * @see #isDrawingCacheEnabled()
3072 *
3073 * @attr ref android.R.styleable#View_drawingCacheQuality
3074 */
3075 public void setDrawingCacheQuality(int quality) {
3076 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3077 }
3078
3079 /**
3080 * Returns whether the screen should remain on, corresponding to the current
3081 * value of {@link #KEEP_SCREEN_ON}.
3082 *
3083 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3084 *
3085 * @see #setKeepScreenOn(boolean)
3086 *
3087 * @attr ref android.R.styleable#View_keepScreenOn
3088 */
3089 public boolean getKeepScreenOn() {
3090 return (mViewFlags & KEEP_SCREEN_ON) != 0;
3091 }
3092
3093 /**
3094 * Controls whether the screen should remain on, modifying the
3095 * value of {@link #KEEP_SCREEN_ON}.
3096 *
3097 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3098 *
3099 * @see #getKeepScreenOn()
3100 *
3101 * @attr ref android.R.styleable#View_keepScreenOn
3102 */
3103 public void setKeepScreenOn(boolean keepScreenOn) {
3104 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3105 }
3106
3107 /**
3108 * @return The user specified next focus ID.
3109 *
3110 * @attr ref android.R.styleable#View_nextFocusLeft
3111 */
3112 public int getNextFocusLeftId() {
3113 return mNextFocusLeftId;
3114 }
3115
3116 /**
3117 * Set the id of the view to use for the next focus
3118 *
3119 * @param nextFocusLeftId
3120 *
3121 * @attr ref android.R.styleable#View_nextFocusLeft
3122 */
3123 public void setNextFocusLeftId(int nextFocusLeftId) {
3124 mNextFocusLeftId = nextFocusLeftId;
3125 }
3126
3127 /**
3128 * @return The user specified next focus ID.
3129 *
3130 * @attr ref android.R.styleable#View_nextFocusRight
3131 */
3132 public int getNextFocusRightId() {
3133 return mNextFocusRightId;
3134 }
3135
3136 /**
3137 * Set the id of the view to use for the next focus
3138 *
3139 * @param nextFocusRightId
3140 *
3141 * @attr ref android.R.styleable#View_nextFocusRight
3142 */
3143 public void setNextFocusRightId(int nextFocusRightId) {
3144 mNextFocusRightId = nextFocusRightId;
3145 }
3146
3147 /**
3148 * @return The user specified next focus ID.
3149 *
3150 * @attr ref android.R.styleable#View_nextFocusUp
3151 */
3152 public int getNextFocusUpId() {
3153 return mNextFocusUpId;
3154 }
3155
3156 /**
3157 * Set the id of the view to use for the next focus
3158 *
3159 * @param nextFocusUpId
3160 *
3161 * @attr ref android.R.styleable#View_nextFocusUp
3162 */
3163 public void setNextFocusUpId(int nextFocusUpId) {
3164 mNextFocusUpId = nextFocusUpId;
3165 }
3166
3167 /**
3168 * @return The user specified next focus ID.
3169 *
3170 * @attr ref android.R.styleable#View_nextFocusDown
3171 */
3172 public int getNextFocusDownId() {
3173 return mNextFocusDownId;
3174 }
3175
3176 /**
3177 * Set the id of the view to use for the next focus
3178 *
3179 * @param nextFocusDownId
3180 *
3181 * @attr ref android.R.styleable#View_nextFocusDown
3182 */
3183 public void setNextFocusDownId(int nextFocusDownId) {
3184 mNextFocusDownId = nextFocusDownId;
3185 }
3186
3187 /**
3188 * Returns the visibility of this view and all of its ancestors
3189 *
3190 * @return True if this view and all of its ancestors are {@link #VISIBLE}
3191 */
3192 public boolean isShown() {
3193 View current = this;
3194 //noinspection ConstantConditions
3195 do {
3196 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3197 return false;
3198 }
3199 ViewParent parent = current.mParent;
3200 if (parent == null) {
3201 return false; // We are not attached to the view root
3202 }
3203 if (!(parent instanceof View)) {
3204 return true;
3205 }
3206 current = (View) parent;
3207 } while (current != null);
3208
3209 return false;
3210 }
3211
3212 /**
3213 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3214 * is set
3215 *
3216 * @param insets Insets for system windows
3217 *
3218 * @return True if this view applied the insets, false otherwise
3219 */
3220 protected boolean fitSystemWindows(Rect insets) {
3221 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3222 mPaddingLeft = insets.left;
3223 mPaddingTop = insets.top;
3224 mPaddingRight = insets.right;
3225 mPaddingBottom = insets.bottom;
3226 requestLayout();
3227 return true;
3228 }
3229 return false;
3230 }
3231
3232 /**
Jim Miller0b2a6d02010-07-13 18:01:29 -07003233 * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3234 * @return True if window has FITS_SYSTEM_WINDOWS set
3235 *
3236 * @hide
3237 */
3238 public boolean isFitsSystemWindowsFlagSet() {
3239 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3240 }
3241
3242 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003243 * Returns the visibility status for this view.
3244 *
3245 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3246 * @attr ref android.R.styleable#View_visibility
3247 */
3248 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003249 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3250 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3251 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 })
3253 public int getVisibility() {
3254 return mViewFlags & VISIBILITY_MASK;
3255 }
3256
3257 /**
3258 * Set the enabled state of this view.
3259 *
3260 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3261 * @attr ref android.R.styleable#View_visibility
3262 */
3263 @RemotableViewMethod
3264 public void setVisibility(int visibility) {
3265 setFlags(visibility, VISIBILITY_MASK);
3266 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3267 }
3268
3269 /**
3270 * Returns the enabled status for this view. The interpretation of the
3271 * enabled state varies by subclass.
3272 *
3273 * @return True if this view is enabled, false otherwise.
3274 */
3275 @ViewDebug.ExportedProperty
3276 public boolean isEnabled() {
3277 return (mViewFlags & ENABLED_MASK) == ENABLED;
3278 }
3279
3280 /**
3281 * Set the enabled state of this view. The interpretation of the enabled
3282 * state varies by subclass.
3283 *
3284 * @param enabled True if this view is enabled, false otherwise.
3285 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003286 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003288 if (enabled == isEnabled()) return;
3289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3291
3292 /*
3293 * The View most likely has to change its appearance, so refresh
3294 * the drawable state.
3295 */
3296 refreshDrawableState();
3297
3298 // Invalidate too, since the default behavior for views is to be
3299 // be drawn at 50% alpha rather than to change the drawable.
3300 invalidate();
3301 }
3302
3303 /**
3304 * Set whether this view can receive the focus.
3305 *
3306 * Setting this to false will also ensure that this view is not focusable
3307 * in touch mode.
3308 *
3309 * @param focusable If true, this view can receive the focus.
3310 *
3311 * @see #setFocusableInTouchMode(boolean)
3312 * @attr ref android.R.styleable#View_focusable
3313 */
3314 public void setFocusable(boolean focusable) {
3315 if (!focusable) {
3316 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3317 }
3318 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3319 }
3320
3321 /**
3322 * Set whether this view can receive focus while in touch mode.
3323 *
3324 * Setting this to true will also ensure that this view is focusable.
3325 *
3326 * @param focusableInTouchMode If true, this view can receive the focus while
3327 * in touch mode.
3328 *
3329 * @see #setFocusable(boolean)
3330 * @attr ref android.R.styleable#View_focusableInTouchMode
3331 */
3332 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3333 // Focusable in touch mode should always be set before the focusable flag
3334 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3335 // which, in touch mode, will not successfully request focus on this view
3336 // because the focusable in touch mode flag is not set
3337 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3338 if (focusableInTouchMode) {
3339 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3340 }
3341 }
3342
3343 /**
3344 * Set whether this view should have sound effects enabled for events such as
3345 * clicking and touching.
3346 *
3347 * <p>You may wish to disable sound effects for a view if you already play sounds,
3348 * for instance, a dial key that plays dtmf tones.
3349 *
3350 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3351 * @see #isSoundEffectsEnabled()
3352 * @see #playSoundEffect(int)
3353 * @attr ref android.R.styleable#View_soundEffectsEnabled
3354 */
3355 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3356 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3357 }
3358
3359 /**
3360 * @return whether this view should have sound effects enabled for events such as
3361 * clicking and touching.
3362 *
3363 * @see #setSoundEffectsEnabled(boolean)
3364 * @see #playSoundEffect(int)
3365 * @attr ref android.R.styleable#View_soundEffectsEnabled
3366 */
3367 @ViewDebug.ExportedProperty
3368 public boolean isSoundEffectsEnabled() {
3369 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3370 }
3371
3372 /**
3373 * Set whether this view should have haptic feedback for events such as
3374 * long presses.
3375 *
3376 * <p>You may wish to disable haptic feedback if your view already controls
3377 * its own haptic feedback.
3378 *
3379 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3380 * @see #isHapticFeedbackEnabled()
3381 * @see #performHapticFeedback(int)
3382 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3383 */
3384 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3385 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3386 }
3387
3388 /**
3389 * @return whether this view should have haptic feedback enabled for events
3390 * long presses.
3391 *
3392 * @see #setHapticFeedbackEnabled(boolean)
3393 * @see #performHapticFeedback(int)
3394 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3395 */
3396 @ViewDebug.ExportedProperty
3397 public boolean isHapticFeedbackEnabled() {
3398 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3399 }
3400
3401 /**
3402 * If this view doesn't do any drawing on its own, set this flag to
3403 * allow further optimizations. By default, this flag is not set on
3404 * View, but could be set on some View subclasses such as ViewGroup.
3405 *
3406 * Typically, if you override {@link #onDraw} you should clear this flag.
3407 *
3408 * @param willNotDraw whether or not this View draw on its own
3409 */
3410 public void setWillNotDraw(boolean willNotDraw) {
3411 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3412 }
3413
3414 /**
3415 * Returns whether or not this View draws on its own.
3416 *
3417 * @return true if this view has nothing to draw, false otherwise
3418 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003419 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 public boolean willNotDraw() {
3421 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3422 }
3423
3424 /**
3425 * When a View's drawing cache is enabled, drawing is redirected to an
3426 * offscreen bitmap. Some views, like an ImageView, must be able to
3427 * bypass this mechanism if they already draw a single bitmap, to avoid
3428 * unnecessary usage of the memory.
3429 *
3430 * @param willNotCacheDrawing true if this view does not cache its
3431 * drawing, false otherwise
3432 */
3433 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3434 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3435 }
3436
3437 /**
3438 * Returns whether or not this View can cache its drawing or not.
3439 *
3440 * @return true if this view does not cache its drawing, false otherwise
3441 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003442 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 public boolean willNotCacheDrawing() {
3444 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3445 }
3446
3447 /**
3448 * Indicates whether this view reacts to click events or not.
3449 *
3450 * @return true if the view is clickable, false otherwise
3451 *
3452 * @see #setClickable(boolean)
3453 * @attr ref android.R.styleable#View_clickable
3454 */
3455 @ViewDebug.ExportedProperty
3456 public boolean isClickable() {
3457 return (mViewFlags & CLICKABLE) == CLICKABLE;
3458 }
3459
3460 /**
3461 * Enables or disables click events for this view. When a view
3462 * is clickable it will change its state to "pressed" on every click.
3463 * Subclasses should set the view clickable to visually react to
3464 * user's clicks.
3465 *
3466 * @param clickable true to make the view clickable, false otherwise
3467 *
3468 * @see #isClickable()
3469 * @attr ref android.R.styleable#View_clickable
3470 */
3471 public void setClickable(boolean clickable) {
3472 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3473 }
3474
3475 /**
3476 * Indicates whether this view reacts to long click events or not.
3477 *
3478 * @return true if the view is long clickable, false otherwise
3479 *
3480 * @see #setLongClickable(boolean)
3481 * @attr ref android.R.styleable#View_longClickable
3482 */
3483 public boolean isLongClickable() {
3484 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3485 }
3486
3487 /**
3488 * Enables or disables long click events for this view. When a view is long
3489 * clickable it reacts to the user holding down the button for a longer
3490 * duration than a tap. This event can either launch the listener or a
3491 * context menu.
3492 *
3493 * @param longClickable true to make the view long clickable, false otherwise
3494 * @see #isLongClickable()
3495 * @attr ref android.R.styleable#View_longClickable
3496 */
3497 public void setLongClickable(boolean longClickable) {
3498 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3499 }
3500
3501 /**
Chet Haase49afa5b2010-08-23 11:39:53 -07003502 * Sets the pressed state for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 *
3504 * @see #isClickable()
3505 * @see #setClickable(boolean)
3506 *
3507 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3508 * the View's internal state from a previously set "pressed" state.
3509 */
3510 public void setPressed(boolean pressed) {
3511 if (pressed) {
3512 mPrivateFlags |= PRESSED;
3513 } else {
3514 mPrivateFlags &= ~PRESSED;
3515 }
3516 refreshDrawableState();
3517 dispatchSetPressed(pressed);
3518 }
3519
3520 /**
3521 * Dispatch setPressed to all of this View's children.
3522 *
3523 * @see #setPressed(boolean)
3524 *
3525 * @param pressed The new pressed state
3526 */
3527 protected void dispatchSetPressed(boolean pressed) {
3528 }
3529
3530 /**
3531 * Indicates whether the view is currently in pressed state. Unless
3532 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3533 * the pressed state.
3534 *
3535 * @see #setPressed
3536 * @see #isClickable()
3537 * @see #setClickable(boolean)
3538 *
3539 * @return true if the view is currently pressed, false otherwise
3540 */
3541 public boolean isPressed() {
3542 return (mPrivateFlags & PRESSED) == PRESSED;
3543 }
3544
3545 /**
3546 * Indicates whether this view will save its state (that is,
3547 * whether its {@link #onSaveInstanceState} method will be called).
3548 *
3549 * @return Returns true if the view state saving is enabled, else false.
3550 *
3551 * @see #setSaveEnabled(boolean)
3552 * @attr ref android.R.styleable#View_saveEnabled
3553 */
3554 public boolean isSaveEnabled() {
3555 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3556 }
3557
3558 /**
3559 * Controls whether the saving of this view's state is
3560 * enabled (that is, whether its {@link #onSaveInstanceState} method
3561 * will be called). Note that even if freezing is enabled, the
3562 * view still must have an id assigned to it (via {@link #setId setId()})
3563 * for its state to be saved. This flag can only disable the
3564 * saving of this view; any child views may still have their state saved.
3565 *
3566 * @param enabled Set to false to <em>disable</em> state saving, or true
3567 * (the default) to allow it.
3568 *
3569 * @see #isSaveEnabled()
3570 * @see #setId(int)
3571 * @see #onSaveInstanceState()
3572 * @attr ref android.R.styleable#View_saveEnabled
3573 */
3574 public void setSaveEnabled(boolean enabled) {
3575 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3576 }
3577
Jeff Brown85a31762010-09-01 17:01:00 -07003578 /**
3579 * Gets whether the framework should discard touches when the view's
3580 * window is obscured by another visible window.
3581 * Refer to the {@link View} security documentation for more details.
3582 *
3583 * @return True if touch filtering is enabled.
3584 *
3585 * @see #setFilterTouchesWhenObscured(boolean)
3586 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3587 */
3588 @ViewDebug.ExportedProperty
3589 public boolean getFilterTouchesWhenObscured() {
3590 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3591 }
3592
3593 /**
3594 * Sets whether the framework should discard touches when the view's
3595 * window is obscured by another visible window.
3596 * Refer to the {@link View} security documentation for more details.
3597 *
3598 * @param enabled True if touch filtering should be enabled.
3599 *
3600 * @see #getFilterTouchesWhenObscured
3601 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3602 */
3603 public void setFilterTouchesWhenObscured(boolean enabled) {
3604 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3605 FILTER_TOUCHES_WHEN_OBSCURED);
3606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607
3608 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003609 * Indicates whether the entire hierarchy under this view will save its
3610 * state when a state saving traversal occurs from its parent. The default
3611 * is true; if false, these views will not be saved unless
3612 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3613 *
3614 * @return Returns true if the view state saving from parent is enabled, else false.
3615 *
3616 * @see #setSaveFromParentEnabled(boolean)
3617 */
3618 public boolean isSaveFromParentEnabled() {
3619 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
3620 }
3621
3622 /**
3623 * Controls whether the entire hierarchy under this view will save its
3624 * state when a state saving traversal occurs from its parent. The default
3625 * is true; if false, these views will not be saved unless
3626 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3627 *
3628 * @param enabled Set to false to <em>disable</em> state saving, or true
3629 * (the default) to allow it.
3630 *
3631 * @see #isSaveFromParentEnabled()
3632 * @see #setId(int)
3633 * @see #onSaveInstanceState()
3634 */
3635 public void setSaveFromParentEnabled(boolean enabled) {
3636 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
3637 }
3638
3639
3640 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 * Returns whether this View is able to take focus.
3642 *
3643 * @return True if this view can take focus, or false otherwise.
3644 * @attr ref android.R.styleable#View_focusable
3645 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003646 @ViewDebug.ExportedProperty(category = "focus")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 public final boolean isFocusable() {
3648 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3649 }
3650
3651 /**
3652 * When a view is focusable, it may not want to take focus when in touch mode.
3653 * For example, a button would like focus when the user is navigating via a D-pad
3654 * so that the user can click on it, but once the user starts touching the screen,
3655 * the button shouldn't take focus
3656 * @return Whether the view is focusable in touch mode.
3657 * @attr ref android.R.styleable#View_focusableInTouchMode
3658 */
3659 @ViewDebug.ExportedProperty
3660 public final boolean isFocusableInTouchMode() {
3661 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3662 }
3663
3664 /**
3665 * Find the nearest view in the specified direction that can take focus.
3666 * This does not actually give focus to that view.
3667 *
3668 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3669 *
3670 * @return The nearest focusable in the specified direction, or null if none
3671 * can be found.
3672 */
3673 public View focusSearch(int direction) {
3674 if (mParent != null) {
3675 return mParent.focusSearch(this, direction);
3676 } else {
3677 return null;
3678 }
3679 }
3680
3681 /**
3682 * This method is the last chance for the focused view and its ancestors to
3683 * respond to an arrow key. This is called when the focused view did not
3684 * consume the key internally, nor could the view system find a new view in
3685 * the requested direction to give focus to.
3686 *
3687 * @param focused The currently focused view.
3688 * @param direction The direction focus wants to move. One of FOCUS_UP,
3689 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3690 * @return True if the this view consumed this unhandled move.
3691 */
3692 public boolean dispatchUnhandledMove(View focused, int direction) {
3693 return false;
3694 }
3695
3696 /**
3697 * If a user manually specified the next view id for a particular direction,
3698 * use the root to look up the view. Once a view is found, it is cached
3699 * for future lookups.
3700 * @param root The root view of the hierarchy containing this view.
3701 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3702 * @return The user specified next view, or null if there is none.
3703 */
3704 View findUserSetNextFocus(View root, int direction) {
3705 switch (direction) {
3706 case FOCUS_LEFT:
3707 if (mNextFocusLeftId == View.NO_ID) return null;
3708 return findViewShouldExist(root, mNextFocusLeftId);
3709 case FOCUS_RIGHT:
3710 if (mNextFocusRightId == View.NO_ID) return null;
3711 return findViewShouldExist(root, mNextFocusRightId);
3712 case FOCUS_UP:
3713 if (mNextFocusUpId == View.NO_ID) return null;
3714 return findViewShouldExist(root, mNextFocusUpId);
3715 case FOCUS_DOWN:
3716 if (mNextFocusDownId == View.NO_ID) return null;
3717 return findViewShouldExist(root, mNextFocusDownId);
3718 }
3719 return null;
3720 }
3721
3722 private static View findViewShouldExist(View root, int childViewId) {
3723 View result = root.findViewById(childViewId);
3724 if (result == null) {
3725 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
3726 + "by user for id " + childViewId);
3727 }
3728 return result;
3729 }
3730
3731 /**
3732 * Find and return all focusable views that are descendants of this view,
3733 * possibly including this view if it is focusable itself.
3734 *
3735 * @param direction The direction of the focus
3736 * @return A list of focusable views
3737 */
3738 public ArrayList<View> getFocusables(int direction) {
3739 ArrayList<View> result = new ArrayList<View>(24);
3740 addFocusables(result, direction);
3741 return result;
3742 }
3743
3744 /**
3745 * Add any focusable views that are descendants of this view (possibly
3746 * including this view if it is focusable itself) to views. If we are in touch mode,
3747 * only add views that are also focusable in touch mode.
3748 *
3749 * @param views Focusable views found so far
3750 * @param direction The direction of the focus
3751 */
3752 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003753 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
3754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755
svetoslavganov75986cf2009-05-14 22:28:01 -07003756 /**
3757 * Adds any focusable views that are descendants of this view (possibly
3758 * including this view if it is focusable itself) to views. This method
3759 * adds all focusable views regardless if we are in touch mode or
3760 * only views focusable in touch mode if we are in touch mode depending on
3761 * the focusable mode paramater.
3762 *
3763 * @param views Focusable views found so far or null if all we are interested is
3764 * the number of focusables.
3765 * @param direction The direction of the focus.
3766 * @param focusableMode The type of focusables to be added.
3767 *
3768 * @see #FOCUSABLES_ALL
3769 * @see #FOCUSABLES_TOUCH_MODE
3770 */
3771 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
3772 if (!isFocusable()) {
3773 return;
3774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775
svetoslavganov75986cf2009-05-14 22:28:01 -07003776 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
3777 isInTouchMode() && !isFocusableInTouchMode()) {
3778 return;
3779 }
3780
3781 if (views != null) {
3782 views.add(this);
3783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 }
3785
3786 /**
3787 * Find and return all touchable views that are descendants of this view,
3788 * possibly including this view if it is touchable itself.
3789 *
3790 * @return A list of touchable views
3791 */
3792 public ArrayList<View> getTouchables() {
3793 ArrayList<View> result = new ArrayList<View>();
3794 addTouchables(result);
3795 return result;
3796 }
3797
3798 /**
3799 * Add any touchable views that are descendants of this view (possibly
3800 * including this view if it is touchable itself) to views.
3801 *
3802 * @param views Touchable views found so far
3803 */
3804 public void addTouchables(ArrayList<View> views) {
3805 final int viewFlags = mViewFlags;
3806
3807 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
3808 && (viewFlags & ENABLED_MASK) == ENABLED) {
3809 views.add(this);
3810 }
3811 }
3812
3813 /**
3814 * Call this to try to give focus to a specific view or to one of its
3815 * descendants.
3816 *
3817 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3818 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3819 * while the device is in touch mode.
3820 *
3821 * See also {@link #focusSearch}, which is what you call to say that you
3822 * have focus, and you want your parent to look for the next one.
3823 *
3824 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
3825 * {@link #FOCUS_DOWN} and <code>null</code>.
3826 *
3827 * @return Whether this view or one of its descendants actually took focus.
3828 */
3829 public final boolean requestFocus() {
3830 return requestFocus(View.FOCUS_DOWN);
3831 }
3832
3833
3834 /**
3835 * Call this to try to give focus to a specific view or to one of its
3836 * descendants and give it a hint about what direction focus is heading.
3837 *
3838 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3839 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3840 * while the device is in touch mode.
3841 *
3842 * See also {@link #focusSearch}, which is what you call to say that you
3843 * have focus, and you want your parent to look for the next one.
3844 *
3845 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
3846 * <code>null</code> set for the previously focused rectangle.
3847 *
3848 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3849 * @return Whether this view or one of its descendants actually took focus.
3850 */
3851 public final boolean requestFocus(int direction) {
3852 return requestFocus(direction, null);
3853 }
3854
3855 /**
3856 * Call this to try to give focus to a specific view or to one of its descendants
3857 * and give it hints about the direction and a specific rectangle that the focus
3858 * is coming from. The rectangle can help give larger views a finer grained hint
3859 * about where focus is coming from, and therefore, where to show selection, or
3860 * forward focus change internally.
3861 *
3862 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3863 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3864 * while the device is in touch mode.
3865 *
3866 * A View will not take focus if it is not visible.
3867 *
3868 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
3869 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
3870 *
3871 * See also {@link #focusSearch}, which is what you call to say that you
3872 * have focus, and you want your parent to look for the next one.
3873 *
3874 * You may wish to override this method if your custom {@link View} has an internal
3875 * {@link View} that it wishes to forward the request to.
3876 *
3877 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3878 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
3879 * to give a finer grained hint about where focus is coming from. May be null
3880 * if there is no hint.
3881 * @return Whether this view or one of its descendants actually took focus.
3882 */
3883 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
3884 // need to be focusable
3885 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
3886 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3887 return false;
3888 }
3889
3890 // need to be focusable in touch mode if in touch mode
3891 if (isInTouchMode() &&
3892 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
3893 return false;
3894 }
3895
3896 // need to not have any parents blocking us
3897 if (hasAncestorThatBlocksDescendantFocus()) {
3898 return false;
3899 }
3900
3901 handleFocusGainInternal(direction, previouslyFocusedRect);
3902 return true;
3903 }
3904
3905 /**
3906 * Call this to try to give focus to a specific view or to one of its descendants. This is a
3907 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
3908 * touch mode to request focus when they are touched.
3909 *
3910 * @return Whether this view or one of its descendants actually took focus.
3911 *
3912 * @see #isInTouchMode()
3913 *
3914 */
3915 public final boolean requestFocusFromTouch() {
3916 // Leave touch mode if we need to
3917 if (isInTouchMode()) {
3918 View root = getRootView();
3919 if (root != null) {
3920 ViewRoot viewRoot = (ViewRoot)root.getParent();
3921 if (viewRoot != null) {
3922 viewRoot.ensureTouchMode(false);
3923 }
3924 }
3925 }
3926 return requestFocus(View.FOCUS_DOWN);
3927 }
3928
3929 /**
3930 * @return Whether any ancestor of this view blocks descendant focus.
3931 */
3932 private boolean hasAncestorThatBlocksDescendantFocus() {
3933 ViewParent ancestor = mParent;
3934 while (ancestor instanceof ViewGroup) {
3935 final ViewGroup vgAncestor = (ViewGroup) ancestor;
3936 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
3937 return true;
3938 } else {
3939 ancestor = vgAncestor.getParent();
3940 }
3941 }
3942 return false;
3943 }
3944
3945 /**
Romain Guya440b002010-02-24 15:57:54 -08003946 * @hide
3947 */
3948 public void dispatchStartTemporaryDetach() {
3949 onStartTemporaryDetach();
3950 }
3951
3952 /**
3953 * This is called when a container is going to temporarily detach a child, with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
3955 * It will either be followed by {@link #onFinishTemporaryDetach()} or
Romain Guya440b002010-02-24 15:57:54 -08003956 * {@link #onDetachedFromWindow()} when the container is done.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 */
3958 public void onStartTemporaryDetach() {
Romain Guya440b002010-02-24 15:57:54 -08003959 removeUnsetPressCallback();
Romain Guy8afa5152010-02-26 11:56:30 -08003960 mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08003961 }
3962
3963 /**
3964 * @hide
3965 */
3966 public void dispatchFinishTemporaryDetach() {
3967 onFinishTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 }
Romain Guy8506ab42009-06-11 17:35:47 -07003969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 /**
3971 * Called after {@link #onStartTemporaryDetach} when the container is done
3972 * changing the view.
3973 */
3974 public void onFinishTemporaryDetach() {
3975 }
Romain Guy8506ab42009-06-11 17:35:47 -07003976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 /**
3978 * capture information of this view for later analysis: developement only
3979 * check dynamic switch to make sure we only dump view
3980 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
3981 */
3982 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003983 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 return;
3985 }
3986 ViewDebug.dumpCapturedView(subTag, v);
3987 }
3988
3989 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003990 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
3991 * for this view's window. Returns null if the view is not currently attached
3992 * to the window. Normally you will not need to use this directly, but
3993 * just use the standard high-level event callbacks like {@link #onKeyDown}.
3994 */
3995 public KeyEvent.DispatcherState getKeyDispatcherState() {
3996 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
3997 }
3998
3999 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 * Dispatch a key event before it is processed by any input method
4001 * associated with the view hierarchy. This can be used to intercept
4002 * key events in special situations before the IME consumes them; a
4003 * typical example would be handling the BACK key to update the application's
4004 * UI instead of allowing the IME to see it and close itself.
4005 *
4006 * @param event The key event to be dispatched.
4007 * @return True if the event was handled, false otherwise.
4008 */
4009 public boolean dispatchKeyEventPreIme(KeyEvent event) {
4010 return onKeyPreIme(event.getKeyCode(), event);
4011 }
4012
4013 /**
4014 * Dispatch a key event to the next view on the focus path. This path runs
4015 * from the top of the view tree down to the currently focused view. If this
4016 * view has focus, it will dispatch to itself. Otherwise it will dispatch
4017 * the next node down the focus path. This method also fires any key
4018 * listeners.
4019 *
4020 * @param event The key event to be dispatched.
4021 * @return True if the event was handled, false otherwise.
4022 */
4023 public boolean dispatchKeyEvent(KeyEvent event) {
4024 // If any attached key listener a first crack at the event.
4025 //noinspection SimplifiableIfStatement
4026
4027 if (android.util.Config.LOGV) {
4028 captureViewInfo("captureViewKeyEvent", this);
4029 }
4030
4031 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4032 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4033 return true;
4034 }
4035
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004036 return event.dispatch(this, mAttachInfo != null
4037 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 }
4039
4040 /**
4041 * Dispatches a key shortcut event.
4042 *
4043 * @param event The key event to be dispatched.
4044 * @return True if the event was handled by the view, false otherwise.
4045 */
4046 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4047 return onKeyShortcut(event.getKeyCode(), event);
4048 }
4049
4050 /**
4051 * Pass the touch screen motion event down to the target view, or this
4052 * view if it is the target.
4053 *
4054 * @param event The motion event to be dispatched.
4055 * @return True if the event was handled by the view, false otherwise.
4056 */
4057 public boolean dispatchTouchEvent(MotionEvent event) {
Jeff Brown85a31762010-09-01 17:01:00 -07004058 if (!onFilterTouchEventForSecurity(event)) {
4059 return false;
4060 }
4061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004062 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4063 mOnTouchListener.onTouch(this, event)) {
4064 return true;
4065 }
4066 return onTouchEvent(event);
4067 }
4068
4069 /**
Jeff Brown85a31762010-09-01 17:01:00 -07004070 * Filter the touch event to apply security policies.
4071 *
4072 * @param event The motion event to be filtered.
4073 * @return True if the event should be dispatched, false if the event should be dropped.
4074 *
4075 * @see #getFilterTouchesWhenObscured
4076 */
4077 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
4078 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4079 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4080 // Window is obscured, drop this touch.
4081 return false;
4082 }
4083 return true;
4084 }
4085
4086 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 * Pass a trackball motion event down to the focused view.
4088 *
4089 * @param event The motion event to be dispatched.
4090 * @return True if the event was handled by the view, false otherwise.
4091 */
4092 public boolean dispatchTrackballEvent(MotionEvent event) {
4093 //Log.i("view", "view=" + this + ", " + event.toString());
4094 return onTrackballEvent(event);
4095 }
4096
4097 /**
4098 * Called when the window containing this view gains or loses window focus.
4099 * ViewGroups should override to route to their children.
4100 *
4101 * @param hasFocus True if the window containing this view now has focus,
4102 * false otherwise.
4103 */
4104 public void dispatchWindowFocusChanged(boolean hasFocus) {
4105 onWindowFocusChanged(hasFocus);
4106 }
4107
4108 /**
4109 * Called when the window containing this view gains or loses focus. Note
4110 * that this is separate from view focus: to receive key events, both
4111 * your view and its window must have focus. If a window is displayed
4112 * on top of yours that takes input focus, then your own window will lose
4113 * focus but the view focus will remain unchanged.
4114 *
4115 * @param hasWindowFocus True if the window containing this view now has
4116 * focus, false otherwise.
4117 */
4118 public void onWindowFocusChanged(boolean hasWindowFocus) {
4119 InputMethodManager imm = InputMethodManager.peekInstance();
4120 if (!hasWindowFocus) {
4121 if (isPressed()) {
4122 setPressed(false);
4123 }
4124 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4125 imm.focusOut(this);
4126 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004127 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07004128 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4130 imm.focusIn(this);
4131 }
4132 refreshDrawableState();
4133 }
4134
4135 /**
4136 * Returns true if this view is in a window that currently has window focus.
4137 * Note that this is not the same as the view itself having focus.
4138 *
4139 * @return True if this view is in a window that currently has window focus.
4140 */
4141 public boolean hasWindowFocus() {
4142 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4143 }
4144
4145 /**
Adam Powell326d8082009-12-09 15:10:07 -08004146 * Dispatch a view visibility change down the view hierarchy.
4147 * ViewGroups should override to route to their children.
4148 * @param changedView The view whose visibility changed. Could be 'this' or
4149 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004150 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4151 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004152 */
4153 protected void dispatchVisibilityChanged(View changedView, int visibility) {
4154 onVisibilityChanged(changedView, visibility);
4155 }
4156
4157 /**
4158 * Called when the visibility of the view or an ancestor of the view is changed.
4159 * @param changedView The view whose visibility changed. Could be 'this' or
4160 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08004161 * @param visibility The new visibility of changedView: {@link #VISIBLE},
4162 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08004163 */
4164 protected void onVisibilityChanged(View changedView, int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004165 if (visibility == VISIBLE) {
4166 if (mAttachInfo != null) {
4167 initialAwakenScrollBars();
4168 } else {
4169 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4170 }
4171 }
Adam Powell326d8082009-12-09 15:10:07 -08004172 }
4173
4174 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08004175 * Dispatch a hint about whether this view is displayed. For instance, when
4176 * a View moves out of the screen, it might receives a display hint indicating
4177 * the view is not displayed. Applications should not <em>rely</em> on this hint
4178 * as there is no guarantee that they will receive one.
4179 *
4180 * @param hint A hint about whether or not this view is displayed:
4181 * {@link #VISIBLE} or {@link #INVISIBLE}.
4182 */
4183 public void dispatchDisplayHint(int hint) {
4184 onDisplayHint(hint);
4185 }
4186
4187 /**
4188 * Gives this view a hint about whether is displayed or not. For instance, when
4189 * a View moves out of the screen, it might receives a display hint indicating
4190 * the view is not displayed. Applications should not <em>rely</em> on this hint
4191 * as there is no guarantee that they will receive one.
4192 *
4193 * @param hint A hint about whether or not this view is displayed:
4194 * {@link #VISIBLE} or {@link #INVISIBLE}.
4195 */
4196 protected void onDisplayHint(int hint) {
4197 }
4198
4199 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 * Dispatch a window visibility change down the view hierarchy.
4201 * ViewGroups should override to route to their children.
4202 *
4203 * @param visibility The new visibility of the window.
4204 *
4205 * @see #onWindowVisibilityChanged
4206 */
4207 public void dispatchWindowVisibilityChanged(int visibility) {
4208 onWindowVisibilityChanged(visibility);
4209 }
4210
4211 /**
4212 * Called when the window containing has change its visibility
4213 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
4214 * that this tells you whether or not your window is being made visible
4215 * to the window manager; this does <em>not</em> tell you whether or not
4216 * your window is obscured by other windows on the screen, even if it
4217 * is itself visible.
4218 *
4219 * @param visibility The new visibility of the window.
4220 */
4221 protected void onWindowVisibilityChanged(int visibility) {
Adam Powell8568c3a2010-04-19 14:26:11 -07004222 if (visibility == VISIBLE) {
4223 initialAwakenScrollBars();
4224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 }
4226
4227 /**
4228 * Returns the current visibility of the window this view is attached to
4229 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4230 *
4231 * @return Returns the current visibility of the view's window.
4232 */
4233 public int getWindowVisibility() {
4234 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4235 }
4236
4237 /**
4238 * Retrieve the overall visible display size in which the window this view is
4239 * attached to has been positioned in. This takes into account screen
4240 * decorations above the window, for both cases where the window itself
4241 * is being position inside of them or the window is being placed under
4242 * then and covered insets are used for the window to position its content
4243 * inside. In effect, this tells you the available area where content can
4244 * be placed and remain visible to users.
4245 *
4246 * <p>This function requires an IPC back to the window manager to retrieve
4247 * the requested information, so should not be used in performance critical
4248 * code like drawing.
4249 *
4250 * @param outRect Filled in with the visible display frame. If the view
4251 * is not attached to a window, this is simply the raw display size.
4252 */
4253 public void getWindowVisibleDisplayFrame(Rect outRect) {
4254 if (mAttachInfo != null) {
4255 try {
4256 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4257 } catch (RemoteException e) {
4258 return;
4259 }
4260 // XXX This is really broken, and probably all needs to be done
4261 // in the window manager, and we need to know more about whether
4262 // we want the area behind or in front of the IME.
4263 final Rect insets = mAttachInfo.mVisibleInsets;
4264 outRect.left += insets.left;
4265 outRect.top += insets.top;
4266 outRect.right -= insets.right;
4267 outRect.bottom -= insets.bottom;
4268 return;
4269 }
4270 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4271 outRect.set(0, 0, d.getWidth(), d.getHeight());
4272 }
4273
4274 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004275 * Dispatch a notification about a resource configuration change down
4276 * the view hierarchy.
4277 * ViewGroups should override to route to their children.
4278 *
4279 * @param newConfig The new resource configuration.
4280 *
4281 * @see #onConfigurationChanged
4282 */
4283 public void dispatchConfigurationChanged(Configuration newConfig) {
4284 onConfigurationChanged(newConfig);
4285 }
4286
4287 /**
4288 * Called when the current configuration of the resources being used
4289 * by the application have changed. You can use this to decide when
4290 * to reload resources that can changed based on orientation and other
4291 * configuration characterstics. You only need to use this if you are
4292 * not relying on the normal {@link android.app.Activity} mechanism of
4293 * recreating the activity instance upon a configuration change.
4294 *
4295 * @param newConfig The new resource configuration.
4296 */
4297 protected void onConfigurationChanged(Configuration newConfig) {
4298 }
4299
4300 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 * Private function to aggregate all per-view attributes in to the view
4302 * root.
4303 */
4304 void dispatchCollectViewAttributes(int visibility) {
4305 performCollectViewAttributes(visibility);
4306 }
4307
4308 void performCollectViewAttributes(int visibility) {
4309 //noinspection PointlessBitwiseExpression
4310 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4311 == (VISIBLE | KEEP_SCREEN_ON)) {
4312 mAttachInfo.mKeepScreenOn = true;
4313 }
4314 }
4315
4316 void needGlobalAttributesUpdate(boolean force) {
4317 AttachInfo ai = mAttachInfo;
4318 if (ai != null) {
4319 if (ai.mKeepScreenOn || force) {
4320 ai.mRecomputeGlobalAttributes = true;
4321 }
4322 }
4323 }
4324
4325 /**
4326 * Returns whether the device is currently in touch mode. Touch mode is entered
4327 * once the user begins interacting with the device by touch, and affects various
4328 * things like whether focus is always visible to the user.
4329 *
4330 * @return Whether the device is in touch mode.
4331 */
4332 @ViewDebug.ExportedProperty
4333 public boolean isInTouchMode() {
4334 if (mAttachInfo != null) {
4335 return mAttachInfo.mInTouchMode;
4336 } else {
4337 return ViewRoot.isInTouchMode();
4338 }
4339 }
4340
4341 /**
4342 * Returns the context the view is running in, through which it can
4343 * access the current theme, resources, etc.
4344 *
4345 * @return The view's Context.
4346 */
4347 @ViewDebug.CapturedViewProperty
4348 public final Context getContext() {
4349 return mContext;
4350 }
4351
4352 /**
4353 * Handle a key event before it is processed by any input method
4354 * associated with the view hierarchy. This can be used to intercept
4355 * key events in special situations before the IME consumes them; a
4356 * typical example would be handling the BACK key to update the application's
4357 * UI instead of allowing the IME to see it and close itself.
4358 *
4359 * @param keyCode The value in event.getKeyCode().
4360 * @param event Description of the key event.
4361 * @return If you handled the event, return true. If you want to allow the
4362 * event to be handled by the next receiver, return false.
4363 */
4364 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4365 return false;
4366 }
4367
4368 /**
4369 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4370 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
4371 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4372 * is released, if the view is enabled and clickable.
4373 *
4374 * @param keyCode A key code that represents the button pressed, from
4375 * {@link android.view.KeyEvent}.
4376 * @param event The KeyEvent object that defines the button action.
4377 */
4378 public boolean onKeyDown(int keyCode, KeyEvent event) {
4379 boolean result = false;
4380
4381 switch (keyCode) {
4382 case KeyEvent.KEYCODE_DPAD_CENTER:
4383 case KeyEvent.KEYCODE_ENTER: {
4384 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4385 return true;
4386 }
4387 // Long clickable items don't necessarily have to be clickable
4388 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4389 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4390 (event.getRepeatCount() == 0)) {
4391 setPressed(true);
4392 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004393 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 }
4395 return true;
4396 }
4397 break;
4398 }
4399 }
4400 return result;
4401 }
4402
4403 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004404 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4405 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4406 * the event).
4407 */
4408 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4409 return false;
4410 }
4411
4412 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004413 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4414 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
4415 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4416 * {@link KeyEvent#KEYCODE_ENTER} is released.
4417 *
4418 * @param keyCode A key code that represents the button pressed, from
4419 * {@link android.view.KeyEvent}.
4420 * @param event The KeyEvent object that defines the button action.
4421 */
4422 public boolean onKeyUp(int keyCode, KeyEvent event) {
4423 boolean result = false;
4424
4425 switch (keyCode) {
4426 case KeyEvent.KEYCODE_DPAD_CENTER:
4427 case KeyEvent.KEYCODE_ENTER: {
4428 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4429 return true;
4430 }
4431 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4432 setPressed(false);
4433
4434 if (!mHasPerformedLongPress) {
4435 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004436 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004437
4438 result = performClick();
4439 }
4440 }
4441 break;
4442 }
4443 }
4444 return result;
4445 }
4446
4447 /**
4448 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4449 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4450 * the event).
4451 *
4452 * @param keyCode A key code that represents the button pressed, from
4453 * {@link android.view.KeyEvent}.
4454 * @param repeatCount The number of times the action was made.
4455 * @param event The KeyEvent object that defines the button action.
4456 */
4457 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4458 return false;
4459 }
4460
4461 /**
4462 * Called when an unhandled key shortcut event occurs.
4463 *
4464 * @param keyCode The value in event.getKeyCode().
4465 * @param event Description of the key event.
4466 * @return If you handled the event, return true. If you want to allow the
4467 * event to be handled by the next receiver, return false.
4468 */
4469 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4470 return false;
4471 }
4472
4473 /**
4474 * Check whether the called view is a text editor, in which case it
4475 * would make sense to automatically display a soft input window for
4476 * it. Subclasses should override this if they implement
4477 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004478 * a call on that method would return a non-null InputConnection, and
4479 * they are really a first-class editor that the user would normally
4480 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004481 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004482 * <p>The default implementation always returns false. This does
4483 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4484 * will not be called or the user can not otherwise perform edits on your
4485 * view; it is just a hint to the system that this is not the primary
4486 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004487 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 * @return Returns true if this view is a text editor, else false.
4489 */
4490 public boolean onCheckIsTextEditor() {
4491 return false;
4492 }
Romain Guy8506ab42009-06-11 17:35:47 -07004493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004494 /**
4495 * Create a new InputConnection for an InputMethod to interact
4496 * with the view. The default implementation returns null, since it doesn't
4497 * support input methods. You can override this to implement such support.
4498 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004499 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500 * <p>When implementing this, you probably also want to implement
4501 * {@link #onCheckIsTextEditor()} to indicate you will return a
4502 * non-null InputConnection.
4503 *
4504 * @param outAttrs Fill in with attribute information about the connection.
4505 */
4506 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4507 return null;
4508 }
4509
4510 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004511 * Called by the {@link android.view.inputmethod.InputMethodManager}
4512 * when a view who is not the current
4513 * input connection target is trying to make a call on the manager. The
4514 * default implementation returns false; you can override this to return
4515 * true for certain views if you are performing InputConnection proxying
4516 * to them.
4517 * @param view The View that is making the InputMethodManager call.
4518 * @return Return true to allow the call, false to reject.
4519 */
4520 public boolean checkInputConnectionProxy(View view) {
4521 return false;
4522 }
Romain Guy8506ab42009-06-11 17:35:47 -07004523
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004524 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 * Show the context menu for this view. It is not safe to hold on to the
4526 * menu after returning from this method.
4527 *
Gilles Debunnef788a9f2010-07-22 10:17:23 -07004528 * You should normally not overload this method. Overload
4529 * {@link #onCreateContextMenu(ContextMenu)} or define an
4530 * {@link OnCreateContextMenuListener} to add items to the context menu.
4531 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 * @param menu The context menu to populate
4533 */
4534 public void createContextMenu(ContextMenu menu) {
4535 ContextMenuInfo menuInfo = getContextMenuInfo();
4536
4537 // Sets the current menu info so all items added to menu will have
4538 // my extra info set.
4539 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4540
4541 onCreateContextMenu(menu);
4542 if (mOnCreateContextMenuListener != null) {
4543 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4544 }
4545
4546 // Clear the extra information so subsequent items that aren't mine don't
4547 // have my extra info.
4548 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4549
4550 if (mParent != null) {
4551 mParent.createContextMenu(menu);
4552 }
4553 }
4554
4555 /**
4556 * Views should implement this if they have extra information to associate
4557 * with the context menu. The return result is supplied as a parameter to
4558 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4559 * callback.
4560 *
4561 * @return Extra information about the item for which the context menu
4562 * should be shown. This information will vary across different
4563 * subclasses of View.
4564 */
4565 protected ContextMenuInfo getContextMenuInfo() {
4566 return null;
4567 }
4568
4569 /**
4570 * Views should implement this if the view itself is going to add items to
4571 * the context menu.
4572 *
4573 * @param menu the context menu to populate
4574 */
4575 protected void onCreateContextMenu(ContextMenu menu) {
4576 }
4577
4578 /**
4579 * Implement this method to handle trackball motion events. The
4580 * <em>relative</em> movement of the trackball since the last event
4581 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4582 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4583 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4584 * they will often be fractional values, representing the more fine-grained
4585 * movement information available from a trackball).
4586 *
4587 * @param event The motion event.
4588 * @return True if the event was handled, false otherwise.
4589 */
4590 public boolean onTrackballEvent(MotionEvent event) {
4591 return false;
4592 }
4593
4594 /**
4595 * Implement this method to handle touch screen motion events.
4596 *
4597 * @param event The motion event.
4598 * @return True if the event was handled, false otherwise.
4599 */
4600 public boolean onTouchEvent(MotionEvent event) {
4601 final int viewFlags = mViewFlags;
4602
4603 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4604 // A disabled view that is clickable still consumes the touch
4605 // events, it just doesn't respond to them.
4606 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4607 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4608 }
4609
4610 if (mTouchDelegate != null) {
4611 if (mTouchDelegate.onTouchEvent(event)) {
4612 return true;
4613 }
4614 }
4615
4616 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4617 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4618 switch (event.getAction()) {
4619 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004620 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4621 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 // take focus if we don't have it already and we should in
4623 // touch mode.
4624 boolean focusTaken = false;
4625 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4626 focusTaken = requestFocus();
4627 }
4628
4629 if (!mHasPerformedLongPress) {
4630 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004631 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632
4633 // Only perform take click actions if we were in the pressed state
4634 if (!focusTaken) {
Adam Powella35d7682010-03-12 14:48:13 -08004635 // Use a Runnable and post this rather than calling
4636 // performClick directly. This lets other visual state
4637 // of the view update before click actions start.
4638 if (mPerformClick == null) {
4639 mPerformClick = new PerformClick();
4640 }
4641 if (!post(mPerformClick)) {
4642 performClick();
4643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 }
4645 }
4646
4647 if (mUnsetPressedState == null) {
4648 mUnsetPressedState = new UnsetPressedState();
4649 }
4650
Adam Powelle14579b2009-12-16 18:39:52 -08004651 if (prepressed) {
4652 mPrivateFlags |= PRESSED;
4653 refreshDrawableState();
4654 postDelayed(mUnsetPressedState,
4655 ViewConfiguration.getPressedStateDuration());
4656 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004657 // If the post failed, unpress right now
4658 mUnsetPressedState.run();
4659 }
Adam Powelle14579b2009-12-16 18:39:52 -08004660 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004661 }
4662 break;
4663
4664 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004665 if (mPendingCheckForTap == null) {
4666 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004667 }
Adam Powelle14579b2009-12-16 18:39:52 -08004668 mPrivateFlags |= PREPRESSED;
Adam Powell3b023392010-03-11 16:30:28 -08004669 mHasPerformedLongPress = false;
Adam Powelle14579b2009-12-16 18:39:52 -08004670 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004671 break;
4672
4673 case MotionEvent.ACTION_CANCEL:
4674 mPrivateFlags &= ~PRESSED;
4675 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004676 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677 break;
4678
4679 case MotionEvent.ACTION_MOVE:
4680 final int x = (int) event.getX();
4681 final int y = (int) event.getY();
4682
4683 // Be lenient about moving outside of buttons
Chet Haasec3aa3612010-06-17 08:50:37 -07004684 if (!pointInView(x, y, mTouchSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004685 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004686 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004688 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004689 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004690
4691 // Need to switch from pressed to not pressed
4692 mPrivateFlags &= ~PRESSED;
4693 refreshDrawableState();
4694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004695 }
4696 break;
4697 }
4698 return true;
4699 }
4700
4701 return false;
4702 }
4703
4704 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004705 * Remove the longpress detection timer.
4706 */
4707 private void removeLongPressCallback() {
4708 if (mPendingCheckForLongPress != null) {
4709 removeCallbacks(mPendingCheckForLongPress);
4710 }
4711 }
Adam Powelle14579b2009-12-16 18:39:52 -08004712
4713 /**
Romain Guya440b002010-02-24 15:57:54 -08004714 * Remove the prepress detection timer.
4715 */
4716 private void removeUnsetPressCallback() {
4717 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
4718 setPressed(false);
4719 removeCallbacks(mUnsetPressedState);
4720 }
4721 }
4722
4723 /**
Adam Powelle14579b2009-12-16 18:39:52 -08004724 * Remove the tap detection timer.
4725 */
4726 private void removeTapCallback() {
4727 if (mPendingCheckForTap != null) {
4728 mPrivateFlags &= ~PREPRESSED;
4729 removeCallbacks(mPendingCheckForTap);
4730 }
4731 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004732
4733 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004734 * Cancels a pending long press. Your subclass can use this if you
4735 * want the context menu to come up if the user presses and holds
4736 * at the same place, but you don't want it to come up if they press
4737 * and then move around enough to cause scrolling.
4738 */
4739 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004740 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004741
4742 /*
4743 * The prepressed state handled by the tap callback is a display
4744 * construct, but the tap callback will post a long press callback
4745 * less its own timeout. Remove it here.
4746 */
4747 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 }
4749
4750 /**
4751 * Sets the TouchDelegate for this View.
4752 */
4753 public void setTouchDelegate(TouchDelegate delegate) {
4754 mTouchDelegate = delegate;
4755 }
4756
4757 /**
4758 * Gets the TouchDelegate for this View.
4759 */
4760 public TouchDelegate getTouchDelegate() {
4761 return mTouchDelegate;
4762 }
4763
4764 /**
4765 * Set flags controlling behavior of this view.
4766 *
4767 * @param flags Constant indicating the value which should be set
4768 * @param mask Constant indicating the bit range that should be changed
4769 */
4770 void setFlags(int flags, int mask) {
4771 int old = mViewFlags;
4772 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4773
4774 int changed = mViewFlags ^ old;
4775 if (changed == 0) {
4776 return;
4777 }
4778 int privateFlags = mPrivateFlags;
4779
4780 /* Check if the FOCUSABLE bit has changed */
4781 if (((changed & FOCUSABLE_MASK) != 0) &&
4782 ((privateFlags & HAS_BOUNDS) !=0)) {
4783 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4784 && ((privateFlags & FOCUSED) != 0)) {
4785 /* Give up focus if we are no longer focusable */
4786 clearFocus();
4787 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4788 && ((privateFlags & FOCUSED) == 0)) {
4789 /*
4790 * Tell the view system that we are now available to take focus
4791 * if no one else already has it.
4792 */
4793 if (mParent != null) mParent.focusableViewAvailable(this);
4794 }
4795 }
4796
4797 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4798 if ((changed & VISIBILITY_MASK) != 0) {
4799 /*
4800 * If this view is becoming visible, set the DRAWN flag so that
4801 * the next invalidate() will not be skipped.
4802 */
4803 mPrivateFlags |= DRAWN;
4804
4805 needGlobalAttributesUpdate(true);
4806
4807 // a view becoming visible is worth notifying the parent
4808 // about in case nothing has focus. even if this specific view
4809 // isn't focusable, it may contain something that is, so let
4810 // the root view try to give this focus if nothing else does.
4811 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4812 mParent.focusableViewAvailable(this);
4813 }
4814 }
4815 }
4816
4817 /* Check if the GONE bit has changed */
4818 if ((changed & GONE) != 0) {
4819 needGlobalAttributesUpdate(false);
4820 requestLayout();
4821 invalidate();
4822
Romain Guyecd80ee2009-12-03 17:13:02 -08004823 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
4824 if (hasFocus()) clearFocus();
4825 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826 }
4827 if (mAttachInfo != null) {
4828 mAttachInfo.mViewVisibilityChanged = true;
4829 }
4830 }
4831
4832 /* Check if the VISIBLE bit has changed */
4833 if ((changed & INVISIBLE) != 0) {
4834 needGlobalAttributesUpdate(false);
4835 invalidate();
4836
4837 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
4838 // root view becoming invisible shouldn't clear focus
4839 if (getRootView() != this) {
4840 clearFocus();
4841 }
4842 }
4843 if (mAttachInfo != null) {
4844 mAttachInfo.mViewVisibilityChanged = true;
4845 }
4846 }
4847
Adam Powell326d8082009-12-09 15:10:07 -08004848 if ((changed & VISIBILITY_MASK) != 0) {
4849 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
4850 }
4851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004852 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
4853 destroyDrawingCache();
4854 }
4855
4856 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
4857 destroyDrawingCache();
4858 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4859 }
4860
4861 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
4862 destroyDrawingCache();
4863 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4864 }
4865
4866 if ((changed & DRAW_MASK) != 0) {
4867 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
4868 if (mBGDrawable != null) {
4869 mPrivateFlags &= ~SKIP_DRAW;
4870 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
4871 } else {
4872 mPrivateFlags |= SKIP_DRAW;
4873 }
4874 } else {
4875 mPrivateFlags &= ~SKIP_DRAW;
4876 }
4877 requestLayout();
4878 invalidate();
4879 }
4880
4881 if ((changed & KEEP_SCREEN_ON) != 0) {
4882 if (mParent != null) {
4883 mParent.recomputeViewAttributes(this);
4884 }
4885 }
4886 }
4887
4888 /**
4889 * Change the view's z order in the tree, so it's on top of other sibling
4890 * views
4891 */
4892 public void bringToFront() {
4893 if (mParent != null) {
4894 mParent.bringChildToFront(this);
4895 }
4896 }
4897
4898 /**
4899 * This is called in response to an internal scroll in this view (i.e., the
4900 * view scrolled its own contents). This is typically as a result of
4901 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
4902 * called.
4903 *
4904 * @param l Current horizontal scroll origin.
4905 * @param t Current vertical scroll origin.
4906 * @param oldl Previous horizontal scroll origin.
4907 * @param oldt Previous vertical scroll origin.
4908 */
4909 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4910 mBackgroundSizeChanged = true;
4911
4912 final AttachInfo ai = mAttachInfo;
4913 if (ai != null) {
4914 ai.mViewScrollChanged = true;
4915 }
4916 }
4917
4918 /**
Chet Haase21cd1382010-09-01 17:42:29 -07004919 * Interface definition for a callback to be invoked when the layout bounds of a view
4920 * changes due to layout processing.
4921 */
4922 public interface OnLayoutChangeListener {
4923 /**
4924 * Called when the focus state of a view has changed.
4925 *
4926 * @param v The view whose state has changed.
4927 * @param left The new value of the view's left property.
4928 * @param top The new value of the view's top property.
4929 * @param right The new value of the view's right property.
4930 * @param bottom The new value of the view's bottom property.
4931 * @param oldLeft The previous value of the view's left property.
4932 * @param oldTop The previous value of the view's top property.
4933 * @param oldRight The previous value of the view's right property.
4934 * @param oldBottom The previous value of the view's bottom property.
4935 */
4936 void onLayoutChange(View v, int left, int top, int right, int bottom,
4937 int oldLeft, int oldTop, int oldRight, int oldBottom);
4938 }
4939
4940 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004941 * This is called during layout when the size of this view has changed. If
4942 * you were just added to the view hierarchy, you're called with the old
4943 * values of 0.
4944 *
4945 * @param w Current width of this view.
4946 * @param h Current height of this view.
4947 * @param oldw Old width of this view.
4948 * @param oldh Old height of this view.
4949 */
4950 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
4951 }
4952
4953 /**
4954 * Called by draw to draw the child views. This may be overridden
4955 * by derived classes to gain control just before its children are drawn
4956 * (but after its own view has been drawn).
4957 * @param canvas the canvas on which to draw the view
4958 */
4959 protected void dispatchDraw(Canvas canvas) {
4960 }
4961
4962 /**
4963 * Gets the parent of this view. Note that the parent is a
4964 * ViewParent and not necessarily a View.
4965 *
4966 * @return Parent of this view.
4967 */
4968 public final ViewParent getParent() {
4969 return mParent;
4970 }
4971
4972 /**
4973 * Return the scrolled left position of this view. This is the left edge of
4974 * the displayed part of your view. You do not need to draw any pixels
4975 * farther left, since those are outside of the frame of your view on
4976 * screen.
4977 *
4978 * @return The left edge of the displayed part of your view, in pixels.
4979 */
4980 public final int getScrollX() {
4981 return mScrollX;
4982 }
4983
4984 /**
4985 * Return the scrolled top position of this view. This is the top edge of
4986 * the displayed part of your view. You do not need to draw any pixels above
4987 * it, since those are outside of the frame of your view on screen.
4988 *
4989 * @return The top edge of the displayed part of your view, in pixels.
4990 */
4991 public final int getScrollY() {
4992 return mScrollY;
4993 }
4994
4995 /**
4996 * Return the width of the your view.
4997 *
4998 * @return The width of your view, in pixels.
4999 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005000 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005001 public final int getWidth() {
5002 return mRight - mLeft;
5003 }
5004
5005 /**
5006 * Return the height of your view.
5007 *
5008 * @return The height of your view, in pixels.
5009 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07005010 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005011 public final int getHeight() {
5012 return mBottom - mTop;
5013 }
5014
5015 /**
5016 * Return the visible drawing bounds of your view. Fills in the output
5017 * rectangle with the values from getScrollX(), getScrollY(),
5018 * getWidth(), and getHeight().
5019 *
5020 * @param outRect The (scrolled) drawing bounds of the view.
5021 */
5022 public void getDrawingRect(Rect outRect) {
5023 outRect.left = mScrollX;
5024 outRect.top = mScrollY;
5025 outRect.right = mScrollX + (mRight - mLeft);
5026 outRect.bottom = mScrollY + (mBottom - mTop);
5027 }
5028
5029 /**
5030 * The width of this view as measured in the most recent call to measure().
5031 * This should be used during measurement and layout calculations only. Use
5032 * {@link #getWidth()} to see how wide a view is after layout.
5033 *
5034 * @return The measured width of this view.
5035 */
5036 public final int getMeasuredWidth() {
5037 return mMeasuredWidth;
5038 }
5039
5040 /**
5041 * The height of this view as measured in the most recent call to measure().
5042 * This should be used during measurement and layout calculations only. Use
5043 * {@link #getHeight()} to see how tall a view is after layout.
5044 *
5045 * @return The measured height of this view.
5046 */
5047 public final int getMeasuredHeight() {
5048 return mMeasuredHeight;
5049 }
5050
5051 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005052 * The transform matrix of this view, which is calculated based on the current
5053 * roation, scale, and pivot properties.
5054 *
5055 * @see #getRotation()
5056 * @see #getScaleX()
5057 * @see #getScaleY()
5058 * @see #getPivotX()
5059 * @see #getPivotY()
5060 * @return The current transform matrix for the view
5061 */
5062 public Matrix getMatrix() {
Romain Guy33e72ae2010-07-17 12:40:29 -07005063 hasIdentityMatrix();
5064 return mMatrix;
5065 }
5066
5067 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005068 * Utility function to determine if the value is far enough away from zero to be
5069 * considered non-zero.
5070 * @param value A floating point value to check for zero-ness
5071 * @return whether the passed-in value is far enough away from zero to be considered non-zero
5072 */
5073 private static boolean nonzero(float value) {
5074 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5075 }
5076
5077 /**
Romain Guy33e72ae2010-07-17 12:40:29 -07005078 * Recomputes the transform matrix if necessary.
5079 *
5080 * @return True if the transform matrix is the identity matrix, false otherwise.
5081 */
5082 boolean hasIdentityMatrix() {
Chet Haasec3aa3612010-06-17 08:50:37 -07005083 if (mMatrixDirty) {
5084 // transform-related properties have changed since the last time someone
5085 // asked for the matrix; recalculate it with the current values
Chet Haasefd2b0022010-08-06 13:08:56 -07005086
5087 // Figure out if we need to update the pivot point
5088 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5089 if ((mRight - mLeft) != mPrevWidth && (mBottom - mTop) != mPrevHeight) {
5090 mPrevWidth = mRight - mLeft;
5091 mPrevHeight = mBottom - mTop;
5092 mPivotX = (float) mPrevWidth / 2f;
5093 mPivotY = (float) mPrevHeight / 2f;
5094 }
5095 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005096 mMatrix.reset();
Chet Haase897247b2010-09-09 14:54:47 -07005097 if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5098 mMatrix.setTranslate(mTranslationX, mTranslationY);
5099 mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5100 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5101 } else {
Chet Haasefd2b0022010-08-06 13:08:56 -07005102 if (mCamera == null) {
5103 mCamera = new Camera();
5104 matrix3D = new Matrix();
5105 }
5106 mCamera.save();
Chet Haase897247b2010-09-09 14:54:47 -07005107 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005108 mCamera.rotateX(mRotationX);
5109 mCamera.rotateY(mRotationY);
Chet Haase897247b2010-09-09 14:54:47 -07005110 mCamera.rotateZ(-mRotation);
Chet Haasefd2b0022010-08-06 13:08:56 -07005111 mCamera.getMatrix(matrix3D);
5112 matrix3D.preTranslate(-mPivotX, -mPivotY);
Chet Haase897247b2010-09-09 14:54:47 -07005113 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
Chet Haasefd2b0022010-08-06 13:08:56 -07005114 mMatrix.postConcat(matrix3D);
5115 mCamera.restore();
5116 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005117 mMatrixDirty = false;
5118 mMatrixIsIdentity = mMatrix.isIdentity();
5119 mInverseMatrixDirty = true;
5120 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005121 return mMatrixIsIdentity;
Chet Haasec3aa3612010-06-17 08:50:37 -07005122 }
5123
5124 /**
5125 * Utility method to retrieve the inverse of the current mMatrix property.
5126 * We cache the matrix to avoid recalculating it when transform properties
5127 * have not changed.
5128 *
5129 * @return The inverse of the current matrix of this view.
5130 */
5131 Matrix getInverseMatrix() {
5132 if (mInverseMatrixDirty) {
5133 if (mInverseMatrix == null) {
5134 mInverseMatrix = new Matrix();
5135 }
5136 mMatrix.invert(mInverseMatrix);
5137 mInverseMatrixDirty = false;
5138 }
5139 return mInverseMatrix;
5140 }
5141
5142 /**
5143 * The degrees that the view is rotated around the pivot point.
5144 *
5145 * @see #getPivotX()
5146 * @see #getPivotY()
5147 * @return The degrees of rotation.
5148 */
5149 public float getRotation() {
5150 return mRotation;
5151 }
5152
5153 /**
Chet Haase897247b2010-09-09 14:54:47 -07005154 * Sets the degrees that the view is rotated around the pivot point. Increasing values
5155 * result in clockwise rotation.
Chet Haasec3aa3612010-06-17 08:50:37 -07005156 *
5157 * @param rotation The degrees of rotation.
5158 * @see #getPivotX()
5159 * @see #getPivotY()
5160 */
5161 public void setRotation(float rotation) {
5162 if (mRotation != rotation) {
5163 // Double-invalidation is necessary to capture view's old and new areas
5164 invalidate();
5165 mRotation = rotation;
5166 mMatrixDirty = true;
5167 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5168 invalidate();
5169 }
5170 }
5171
5172 /**
Chet Haasefd2b0022010-08-06 13:08:56 -07005173 * The degrees that the view is rotated around the vertical axis through the pivot point.
5174 *
5175 * @see #getPivotX()
5176 * @see #getPivotY()
5177 * @return The degrees of Y rotation.
5178 */
5179 public float getRotationY() {
5180 return mRotationY;
5181 }
5182
5183 /**
Chet Haase897247b2010-09-09 14:54:47 -07005184 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5185 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5186 * down the y axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005187 *
5188 * @param rotationY The degrees of Y rotation.
5189 * @see #getPivotX()
5190 * @see #getPivotY()
5191 */
5192 public void setRotationY(float rotationY) {
5193 if (mRotationY != rotationY) {
5194 // Double-invalidation is necessary to capture view's old and new areas
5195 invalidate();
5196 mRotationY = rotationY;
5197 mMatrixDirty = true;
5198 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5199 invalidate();
5200 }
5201 }
5202
5203 /**
5204 * The degrees that the view is rotated around the horizontal axis through the pivot point.
5205 *
5206 * @see #getPivotX()
5207 * @see #getPivotY()
5208 * @return The degrees of X rotation.
5209 */
5210 public float getRotationX() {
5211 return mRotationX;
5212 }
5213
5214 /**
Chet Haase897247b2010-09-09 14:54:47 -07005215 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5216 * Increasing values result in clockwise rotation from the viewpoint of looking down the
5217 * x axis.
Chet Haasefd2b0022010-08-06 13:08:56 -07005218 *
5219 * @param rotationX The degrees of X rotation.
5220 * @see #getPivotX()
5221 * @see #getPivotY()
5222 */
5223 public void setRotationX(float rotationX) {
5224 if (mRotationX != rotationX) {
5225 // Double-invalidation is necessary to capture view's old and new areas
5226 invalidate();
5227 mRotationX = rotationX;
5228 mMatrixDirty = true;
5229 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5230 invalidate();
5231 }
5232 }
5233
5234 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005235 * The amount that the view is scaled in x around the pivot point, as a proportion of
5236 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5237 *
5238 * @default 1.0f
5239 * @see #getPivotX()
5240 * @see #getPivotY()
5241 * @return The scaling factor.
5242 */
5243 public float getScaleX() {
5244 return mScaleX;
5245 }
5246
5247 /**
5248 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5249 * the view's unscaled width. A value of 1 means that no scaling is applied.
5250 *
5251 * @param scaleX The scaling factor.
5252 * @see #getPivotX()
5253 * @see #getPivotY()
5254 */
5255 public void setScaleX(float scaleX) {
5256 if (mScaleX != scaleX) {
5257 // Double-invalidation is necessary to capture view's old and new areas
5258 invalidate();
5259 mScaleX = scaleX;
5260 mMatrixDirty = true;
5261 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5262 invalidate();
5263 }
5264 }
5265
5266 /**
5267 * The amount that the view is scaled in y around the pivot point, as a proportion of
5268 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5269 *
5270 * @default 1.0f
5271 * @see #getPivotX()
5272 * @see #getPivotY()
5273 * @return The scaling factor.
5274 */
5275 public float getScaleY() {
5276 return mScaleY;
5277 }
5278
5279 /**
5280 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5281 * the view's unscaled width. A value of 1 means that no scaling is applied.
5282 *
5283 * @param scaleY The scaling factor.
5284 * @see #getPivotX()
5285 * @see #getPivotY()
5286 */
5287 public void setScaleY(float scaleY) {
5288 if (mScaleY != scaleY) {
5289 // Double-invalidation is necessary to capture view's old and new areas
5290 invalidate();
5291 mScaleY = scaleY;
5292 mMatrixDirty = true;
5293 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5294 invalidate();
5295 }
5296 }
5297
5298 /**
5299 * The x location of the point around which the view is {@link #setRotation(float) rotated}
5300 * and {@link #setScaleX(float) scaled}.
5301 *
5302 * @see #getRotation()
5303 * @see #getScaleX()
5304 * @see #getScaleY()
5305 * @see #getPivotY()
5306 * @return The x location of the pivot point.
5307 */
5308 public float getPivotX() {
5309 return mPivotX;
5310 }
5311
5312 /**
5313 * Sets the x location of the point around which the view is
5314 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
Chet Haasefd2b0022010-08-06 13:08:56 -07005315 * By default, the pivot point is centered on the object.
5316 * Setting this property disables this behavior and causes the view to use only the
5317 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005318 *
5319 * @param pivotX The x location of the pivot point.
5320 * @see #getRotation()
5321 * @see #getScaleX()
5322 * @see #getScaleY()
5323 * @see #getPivotY()
5324 */
5325 public void setPivotX(float pivotX) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005326 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005327 if (mPivotX != pivotX) {
5328 // Double-invalidation is necessary to capture view's old and new areas
5329 invalidate();
5330 mPivotX = pivotX;
5331 mMatrixDirty = true;
5332 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5333 invalidate();
5334 }
5335 }
5336
5337 /**
5338 * The y location of the point around which the view is {@link #setRotation(float) rotated}
5339 * and {@link #setScaleY(float) scaled}.
5340 *
5341 * @see #getRotation()
5342 * @see #getScaleX()
5343 * @see #getScaleY()
5344 * @see #getPivotY()
5345 * @return The y location of the pivot point.
5346 */
5347 public float getPivotY() {
5348 return mPivotY;
5349 }
5350
5351 /**
5352 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
Chet Haasefd2b0022010-08-06 13:08:56 -07005353 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5354 * Setting this property disables this behavior and causes the view to use only the
5355 * explicitly set pivotX and pivotY values.
Chet Haasec3aa3612010-06-17 08:50:37 -07005356 *
5357 * @param pivotY The y location of the pivot point.
5358 * @see #getRotation()
5359 * @see #getScaleX()
5360 * @see #getScaleY()
5361 * @see #getPivotY()
5362 */
5363 public void setPivotY(float pivotY) {
Chet Haasefd2b0022010-08-06 13:08:56 -07005364 mPrivateFlags |= PIVOT_EXPLICITLY_SET;
Chet Haasec3aa3612010-06-17 08:50:37 -07005365 if (mPivotY != pivotY) {
5366 // Double-invalidation is necessary to capture view's old and new areas
5367 invalidate();
5368 mPivotY = pivotY;
5369 mMatrixDirty = true;
5370 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5371 invalidate();
5372 }
5373 }
5374
5375 /**
5376 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5377 * completely transparent and 1 means the view is completely opaque.
5378 *
5379 * @default 1.0f
5380 * @return The opacity of the view.
5381 */
5382 public float getAlpha() {
5383 return mAlpha;
5384 }
5385
5386 /**
5387 * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5388 * completely transparent and 1 means the view is completely opaque.
5389 *
5390 * @param alpha The opacity of the view.
5391 */
5392 public void setAlpha(float alpha) {
5393 mAlpha = alpha;
Romain Guy9b34d452010-09-02 11:45:04 -07005394 onSetAlpha((int) (alpha * 255));
Chet Haasec3aa3612010-06-17 08:50:37 -07005395 invalidate();
5396 }
5397
5398 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005399 * Top position of this view relative to its parent.
5400 *
5401 * @return The top of this view, in pixels.
5402 */
5403 @ViewDebug.CapturedViewProperty
5404 public final int getTop() {
5405 return mTop;
5406 }
5407
5408 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005409 * Sets the top position of this view relative to its parent. This method is meant to be called
5410 * by the layout system and should not generally be called otherwise, because the property
5411 * may be changed at any time by the layout.
5412 *
5413 * @param top The top of this view, in pixels.
5414 */
5415 public final void setTop(int top) {
5416 if (top != mTop) {
5417 if (hasIdentityMatrix()) {
5418 final ViewParent p = mParent;
5419 if (p != null && mAttachInfo != null) {
5420 final Rect r = mAttachInfo.mTmpInvalRect;
5421 int minTop;
5422 int yLoc;
5423 if (top < mTop) {
5424 minTop = top;
5425 yLoc = top - mTop;
5426 } else {
5427 minTop = mTop;
5428 yLoc = 0;
5429 }
5430 r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5431 p.invalidateChild(this, r);
5432 }
5433 } else {
5434 // Double-invalidation is necessary to capture view's old and new areas
5435 invalidate();
5436 }
5437
5438 mTop = top;
5439
5440 if (!mMatrixIsIdentity) {
5441 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5442 invalidate();
5443 }
5444 }
5445 }
5446
5447 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 * Bottom position of this view relative to its parent.
5449 *
5450 * @return The bottom of this view, in pixels.
5451 */
5452 @ViewDebug.CapturedViewProperty
5453 public final int getBottom() {
5454 return mBottom;
5455 }
5456
5457 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005458 * Sets the bottom position of this view relative to its parent. This method is meant to be
5459 * called by the layout system and should not generally be called otherwise, because the
5460 * property may be changed at any time by the layout.
5461 *
5462 * @param bottom The bottom of this view, in pixels.
5463 */
5464 public final void setBottom(int bottom) {
5465 if (bottom != mBottom) {
5466 if (hasIdentityMatrix()) {
5467 final ViewParent p = mParent;
5468 if (p != null && mAttachInfo != null) {
5469 final Rect r = mAttachInfo.mTmpInvalRect;
5470 int maxBottom;
5471 if (bottom < mBottom) {
5472 maxBottom = mBottom;
5473 } else {
5474 maxBottom = bottom;
5475 }
5476 r.set(0, 0, mRight - mLeft, maxBottom - mTop);
5477 p.invalidateChild(this, r);
5478 }
5479 } else {
5480 // Double-invalidation is necessary to capture view's old and new areas
5481 invalidate();
5482 }
5483
5484 mBottom = bottom;
5485
5486 if (!mMatrixIsIdentity) {
5487 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5488 invalidate();
5489 }
5490 }
5491 }
5492
5493 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005494 * Left position of this view relative to its parent.
5495 *
5496 * @return The left edge of this view, in pixels.
5497 */
5498 @ViewDebug.CapturedViewProperty
5499 public final int getLeft() {
5500 return mLeft;
5501 }
5502
5503 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005504 * Sets the left position of this view relative to its parent. This method is meant to be called
5505 * by the layout system and should not generally be called otherwise, because the property
5506 * may be changed at any time by the layout.
5507 *
5508 * @param left The bottom of this view, in pixels.
5509 */
5510 public final void setLeft(int left) {
5511 if (left != mLeft) {
5512 System.out.println("view " + this + " left = " + left);
5513 if (hasIdentityMatrix()) {
5514 final ViewParent p = mParent;
5515 if (p != null && mAttachInfo != null) {
5516 final Rect r = mAttachInfo.mTmpInvalRect;
5517 int minLeft;
5518 int xLoc;
5519 if (left < mLeft) {
5520 minLeft = left;
5521 xLoc = left - mLeft;
5522 } else {
5523 minLeft = mLeft;
5524 xLoc = 0;
5525 }
5526 r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
5527 p.invalidateChild(this, r);
5528 }
5529 } else {
5530 // Double-invalidation is necessary to capture view's old and new areas
5531 invalidate();
5532 }
5533
5534 mLeft = left;
5535
5536 if (!mMatrixIsIdentity) {
5537 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5538 invalidate();
5539 }
5540 }
5541 }
5542
5543 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 * Right position of this view relative to its parent.
5545 *
5546 * @return The right edge of this view, in pixels.
5547 */
5548 @ViewDebug.CapturedViewProperty
5549 public final int getRight() {
5550 return mRight;
5551 }
5552
5553 /**
Chet Haase21cd1382010-09-01 17:42:29 -07005554 * Sets the right position of this view relative to its parent. This method is meant to be called
5555 * by the layout system and should not generally be called otherwise, because the property
5556 * may be changed at any time by the layout.
5557 *
5558 * @param right The bottom of this view, in pixels.
5559 */
5560 public final void setRight(int right) {
5561 if (right != mRight) {
5562 if (hasIdentityMatrix()) {
5563 final ViewParent p = mParent;
5564 if (p != null && mAttachInfo != null) {
5565 final Rect r = mAttachInfo.mTmpInvalRect;
5566 int maxRight;
5567 if (right < mRight) {
5568 maxRight = mRight;
5569 } else {
5570 maxRight = right;
5571 }
5572 r.set(0, 0, maxRight - mLeft, mBottom - mTop);
5573 p.invalidateChild(this, r);
5574 }
5575 } else {
5576 // Double-invalidation is necessary to capture view's old and new areas
5577 invalidate();
5578 }
5579
5580 mRight = right;
5581
5582 if (!mMatrixIsIdentity) {
5583 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5584 invalidate();
5585 }
5586 }
5587 }
5588
5589 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005590 * The visual x position of this view, in pixels. This is equivalent to the
5591 * {@link #setTranslationX(float) translationX} property plus the current
5592 * {@link #getLeft() left} property.
Chet Haasec3aa3612010-06-17 08:50:37 -07005593 *
Chet Haasedf030d22010-07-30 17:22:38 -07005594 * @return The visual x position of this view, in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005595 */
Chet Haasedf030d22010-07-30 17:22:38 -07005596 public float getX() {
5597 return mLeft + mTranslationX;
5598 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005599
Chet Haasedf030d22010-07-30 17:22:38 -07005600 /**
5601 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
5602 * {@link #setTranslationX(float) translationX} property to be the difference between
5603 * the x value passed in and the current {@link #getLeft() left} property.
5604 *
5605 * @param x The visual x position of this view, in pixels.
5606 */
5607 public void setX(float x) {
5608 setTranslationX(x - mLeft);
5609 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005610
Chet Haasedf030d22010-07-30 17:22:38 -07005611 /**
5612 * The visual y position of this view, in pixels. This is equivalent to the
5613 * {@link #setTranslationY(float) translationY} property plus the current
5614 * {@link #getTop() top} property.
5615 *
5616 * @return The visual y position of this view, in pixels.
5617 */
5618 public float getY() {
5619 return mTop + mTranslationY;
5620 }
5621
5622 /**
5623 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
5624 * {@link #setTranslationY(float) translationY} property to be the difference between
5625 * the y value passed in and the current {@link #getTop() top} property.
5626 *
5627 * @param y The visual y position of this view, in pixels.
5628 */
5629 public void setY(float y) {
5630 setTranslationY(y - mTop);
5631 }
5632
5633
5634 /**
5635 * The horizontal location of this view relative to its {@link #getLeft() left} position.
5636 * This position is post-layout, in addition to wherever the object's
5637 * layout placed it.
5638 *
5639 * @return The horizontal position of this view relative to its left position, in pixels.
5640 */
5641 public float getTranslationX() {
5642 return mTranslationX;
5643 }
5644
5645 /**
5646 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
5647 * This effectively positions the object post-layout, in addition to wherever the object's
5648 * layout placed it.
5649 *
5650 * @param translationX The horizontal position of this view relative to its left position,
5651 * in pixels.
5652 */
5653 public void setTranslationX(float translationX) {
5654 if (mTranslationX != translationX) {
5655 // Double-invalidation is necessary to capture view's old and new areas
5656 invalidate();
5657 mTranslationX = translationX;
5658 mMatrixDirty = true;
5659 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5660 invalidate();
Chet Haasec3aa3612010-06-17 08:50:37 -07005661 }
5662 }
5663
5664 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005665 * The horizontal location of this view relative to its {@link #getTop() top} position.
5666 * This position is post-layout, in addition to wherever the object's
5667 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005668 *
Chet Haasedf030d22010-07-30 17:22:38 -07005669 * @return The vertical position of this view relative to its top position,
5670 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005671 */
Chet Haasedf030d22010-07-30 17:22:38 -07005672 public float getTranslationY() {
5673 return mTranslationY;
Chet Haasec3aa3612010-06-17 08:50:37 -07005674 }
5675
5676 /**
Chet Haasedf030d22010-07-30 17:22:38 -07005677 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
5678 * This effectively positions the object post-layout, in addition to wherever the object's
5679 * layout placed it.
Chet Haasec3aa3612010-06-17 08:50:37 -07005680 *
Chet Haasedf030d22010-07-30 17:22:38 -07005681 * @param translationY The vertical position of this view relative to its top position,
5682 * in pixels.
Chet Haasec3aa3612010-06-17 08:50:37 -07005683 */
Chet Haasedf030d22010-07-30 17:22:38 -07005684 public void setTranslationY(float translationY) {
5685 if (mTranslationY != translationY) {
5686 // Double-invalidation is necessary to capture view's old and new areas
5687 invalidate();
5688 mTranslationY = translationY;
5689 mMatrixDirty = true;
5690 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5691 invalidate();
5692 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005693 }
5694
5695 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 * Hit rectangle in parent's coordinates
5697 *
5698 * @param outRect The hit rectangle of the view.
5699 */
5700 public void getHitRect(Rect outRect) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005701 if (hasIdentityMatrix() || mAttachInfo == null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005702 outRect.set(mLeft, mTop, mRight, mBottom);
5703 } else {
Adam Powellb5de9f32010-07-17 01:00:53 -07005704 Matrix m = getMatrix();
Chet Haasec3aa3612010-06-17 08:50:37 -07005705 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
Romain Guy33e72ae2010-07-17 12:40:29 -07005706 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
Chet Haasec3aa3612010-06-17 08:50:37 -07005707 m.mapRect(tmpRect);
Romain Guy33e72ae2010-07-17 12:40:29 -07005708 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
5709 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
Chet Haasec3aa3612010-06-17 08:50:37 -07005710 }
5711 }
5712
5713 /**
Chet Haasec3aa3612010-06-17 08:50:37 -07005714 * Utility method to determine whether the given point, in local coordinates,
5715 * is inside the view, where the area of the view is expanded by the slop factor.
5716 * This method is called while processing touch-move events to determine if the event
5717 * is still within the view.
5718 */
5719 private boolean pointInView(float localX, float localY, float slop) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005720 return localX > -slop && localY > -slop && localX < ((mRight - mLeft) + slop) &&
5721 localY < ((mBottom - mTop) + slop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 }
5723
5724 /**
5725 * When a view has focus and the user navigates away from it, the next view is searched for
5726 * starting from the rectangle filled in by this method.
5727 *
5728 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
5729 * view maintains some idea of internal selection, such as a cursor, or a selected row
5730 * or column, you should override this method and fill in a more specific rectangle.
5731 *
5732 * @param r The rectangle to fill in, in this view's coordinates.
5733 */
5734 public void getFocusedRect(Rect r) {
5735 getDrawingRect(r);
5736 }
5737
5738 /**
5739 * If some part of this view is not clipped by any of its parents, then
5740 * return that area in r in global (root) coordinates. To convert r to local
5741 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
5742 * -globalOffset.y)) If the view is completely clipped or translated out,
5743 * return false.
5744 *
5745 * @param r If true is returned, r holds the global coordinates of the
5746 * visible portion of this view.
5747 * @param globalOffset If true is returned, globalOffset holds the dx,dy
5748 * between this view and its root. globalOffet may be null.
5749 * @return true if r is non-empty (i.e. part of the view is visible at the
5750 * root level.
5751 */
5752 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
5753 int width = mRight - mLeft;
5754 int height = mBottom - mTop;
5755 if (width > 0 && height > 0) {
5756 r.set(0, 0, width, height);
5757 if (globalOffset != null) {
5758 globalOffset.set(-mScrollX, -mScrollY);
5759 }
5760 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
5761 }
5762 return false;
5763 }
5764
5765 public final boolean getGlobalVisibleRect(Rect r) {
5766 return getGlobalVisibleRect(r, null);
5767 }
5768
5769 public final boolean getLocalVisibleRect(Rect r) {
5770 Point offset = new Point();
5771 if (getGlobalVisibleRect(r, offset)) {
5772 r.offset(-offset.x, -offset.y); // make r local
5773 return true;
5774 }
5775 return false;
5776 }
5777
5778 /**
5779 * Offset this view's vertical location by the specified number of pixels.
5780 *
5781 * @param offset the number of pixels to offset the view by
5782 */
5783 public void offsetTopAndBottom(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005784 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005785 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005786 final ViewParent p = mParent;
5787 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005788 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005789 int minTop;
5790 int maxBottom;
5791 int yLoc;
5792 if (offset < 0) {
5793 minTop = mTop + offset;
5794 maxBottom = mBottom;
5795 yLoc = offset;
5796 } else {
5797 minTop = mTop;
5798 maxBottom = mBottom + offset;
5799 yLoc = 0;
5800 }
5801 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
5802 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005803 }
5804 } else {
5805 invalidate();
5806 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005807
Chet Haasec3aa3612010-06-17 08:50:37 -07005808 mTop += offset;
5809 mBottom += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005810
Chet Haasec3aa3612010-06-17 08:50:37 -07005811 if (!mMatrixIsIdentity) {
5812 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5813 invalidate();
5814 }
5815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 }
5817
5818 /**
5819 * Offset this view's horizontal location by the specified amount of pixels.
5820 *
5821 * @param offset the numer of pixels to offset the view by
5822 */
5823 public void offsetLeftAndRight(int offset) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005824 if (offset != 0) {
Romain Guy33e72ae2010-07-17 12:40:29 -07005825 if (hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005826 final ViewParent p = mParent;
5827 if (p != null && mAttachInfo != null) {
Chet Haasec3aa3612010-06-17 08:50:37 -07005828 final Rect r = mAttachInfo.mTmpInvalRect;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005829 int minLeft;
5830 int maxRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005831 if (offset < 0) {
5832 minLeft = mLeft + offset;
5833 maxRight = mRight;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005834 } else {
5835 minLeft = mLeft;
5836 maxRight = mRight + offset;
Chet Haase8fbf8d22010-07-30 15:01:32 -07005837 }
Chet Haasec3aa3612010-06-17 08:50:37 -07005838 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
Chet Haase8fbf8d22010-07-30 15:01:32 -07005839 p.invalidateChild(this, r);
Chet Haasec3aa3612010-06-17 08:50:37 -07005840 }
5841 } else {
5842 invalidate();
5843 }
Romain Guy33e72ae2010-07-17 12:40:29 -07005844
Chet Haasec3aa3612010-06-17 08:50:37 -07005845 mLeft += offset;
5846 mRight += offset;
Romain Guy33e72ae2010-07-17 12:40:29 -07005847
Chet Haasec3aa3612010-06-17 08:50:37 -07005848 if (!mMatrixIsIdentity) {
5849 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5850 invalidate();
5851 }
5852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 }
5854
5855 /**
5856 * Get the LayoutParams associated with this view. All views should have
5857 * layout parameters. These supply parameters to the <i>parent</i> of this
5858 * view specifying how it should be arranged. There are many subclasses of
5859 * ViewGroup.LayoutParams, and these correspond to the different subclasses
5860 * of ViewGroup that are responsible for arranging their children.
5861 * @return The LayoutParams associated with this view
5862 */
Konstantin Lopyrev91a7f5f2010-08-10 18:54:54 -07005863 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 public ViewGroup.LayoutParams getLayoutParams() {
5865 return mLayoutParams;
5866 }
5867
5868 /**
5869 * Set the layout parameters associated with this view. These supply
5870 * parameters to the <i>parent</i> of this view specifying how it should be
5871 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
5872 * correspond to the different subclasses of ViewGroup that are responsible
5873 * for arranging their children.
5874 *
5875 * @param params the layout parameters for this view
5876 */
5877 public void setLayoutParams(ViewGroup.LayoutParams params) {
5878 if (params == null) {
5879 throw new NullPointerException("params == null");
5880 }
5881 mLayoutParams = params;
5882 requestLayout();
5883 }
5884
5885 /**
5886 * Set the scrolled position of your view. This will cause a call to
5887 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5888 * invalidated.
5889 * @param x the x position to scroll to
5890 * @param y the y position to scroll to
5891 */
5892 public void scrollTo(int x, int y) {
5893 if (mScrollX != x || mScrollY != y) {
5894 int oldX = mScrollX;
5895 int oldY = mScrollY;
5896 mScrollX = x;
5897 mScrollY = y;
5898 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07005899 if (!awakenScrollBars()) {
5900 invalidate();
5901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005902 }
5903 }
5904
5905 /**
5906 * Move the scrolled position of your view. This will cause a call to
5907 * {@link #onScrollChanged(int, int, int, int)} and the view will be
5908 * invalidated.
5909 * @param x the amount of pixels to scroll by horizontally
5910 * @param y the amount of pixels to scroll by vertically
5911 */
5912 public void scrollBy(int x, int y) {
5913 scrollTo(mScrollX + x, mScrollY + y);
5914 }
5915
5916 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07005917 * <p>Trigger the scrollbars to draw. When invoked this method starts an
5918 * animation to fade the scrollbars out after a default delay. If a subclass
5919 * provides animated scrolling, the start delay should equal the duration
5920 * of the scrolling animation.</p>
5921 *
5922 * <p>The animation starts only if at least one of the scrollbars is
5923 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
5924 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5925 * this method returns true, and false otherwise. If the animation is
5926 * started, this method calls {@link #invalidate()}; in that case the
5927 * caller should not call {@link #invalidate()}.</p>
5928 *
5929 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07005930 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07005931 *
5932 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
5933 * and {@link #scrollTo(int, int)}.</p>
5934 *
5935 * @return true if the animation is played, false otherwise
5936 *
5937 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07005938 * @see #scrollBy(int, int)
5939 * @see #scrollTo(int, int)
5940 * @see #isHorizontalScrollBarEnabled()
5941 * @see #isVerticalScrollBarEnabled()
5942 * @see #setHorizontalScrollBarEnabled(boolean)
5943 * @see #setVerticalScrollBarEnabled(boolean)
5944 */
5945 protected boolean awakenScrollBars() {
5946 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07005947 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07005948 }
5949
5950 /**
Adam Powell8568c3a2010-04-19 14:26:11 -07005951 * Trigger the scrollbars to draw.
5952 * This method differs from awakenScrollBars() only in its default duration.
5953 * initialAwakenScrollBars() will show the scroll bars for longer than
5954 * usual to give the user more of a chance to notice them.
5955 *
5956 * @return true if the animation is played, false otherwise.
5957 */
5958 private boolean initialAwakenScrollBars() {
5959 return mScrollCache != null &&
5960 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
5961 }
5962
5963 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07005964 * <p>
5965 * Trigger the scrollbars to draw. When invoked this method starts an
5966 * animation to fade the scrollbars out after a fixed delay. If a subclass
5967 * provides animated scrolling, the start delay should equal the duration of
5968 * the scrolling animation.
5969 * </p>
5970 *
5971 * <p>
5972 * The animation starts only if at least one of the scrollbars is enabled,
5973 * as specified by {@link #isHorizontalScrollBarEnabled()} and
5974 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
5975 * this method returns true, and false otherwise. If the animation is
5976 * started, this method calls {@link #invalidate()}; in that case the caller
5977 * should not call {@link #invalidate()}.
5978 * </p>
5979 *
5980 * <p>
5981 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07005982 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07005983 * </p>
5984 *
5985 * @param startDelay the delay, in milliseconds, after which the animation
5986 * should start; when the delay is 0, the animation starts
5987 * immediately
5988 * @return true if the animation is played, false otherwise
5989 *
Mike Cleronf116bf82009-09-27 19:14:12 -07005990 * @see #scrollBy(int, int)
5991 * @see #scrollTo(int, int)
5992 * @see #isHorizontalScrollBarEnabled()
5993 * @see #isVerticalScrollBarEnabled()
5994 * @see #setHorizontalScrollBarEnabled(boolean)
5995 * @see #setVerticalScrollBarEnabled(boolean)
5996 */
5997 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07005998 return awakenScrollBars(startDelay, true);
5999 }
6000
6001 /**
6002 * <p>
6003 * Trigger the scrollbars to draw. When invoked this method starts an
6004 * animation to fade the scrollbars out after a fixed delay. If a subclass
6005 * provides animated scrolling, the start delay should equal the duration of
6006 * the scrolling animation.
6007 * </p>
6008 *
6009 * <p>
6010 * The animation starts only if at least one of the scrollbars is enabled,
6011 * as specified by {@link #isHorizontalScrollBarEnabled()} and
6012 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6013 * this method returns true, and false otherwise. If the animation is
6014 * started, this method calls {@link #invalidate()} if the invalidate parameter
6015 * is set to true; in that case the caller
6016 * should not call {@link #invalidate()}.
6017 * </p>
6018 *
6019 * <p>
6020 * This method should be invoked everytime a subclass directly updates the
6021 * scroll parameters.
6022 * </p>
6023 *
6024 * @param startDelay the delay, in milliseconds, after which the animation
6025 * should start; when the delay is 0, the animation starts
6026 * immediately
6027 *
6028 * @param invalidate Wheter this method should call invalidate
6029 *
6030 * @return true if the animation is played, false otherwise
6031 *
6032 * @see #scrollBy(int, int)
6033 * @see #scrollTo(int, int)
6034 * @see #isHorizontalScrollBarEnabled()
6035 * @see #isVerticalScrollBarEnabled()
6036 * @see #setHorizontalScrollBarEnabled(boolean)
6037 * @see #setVerticalScrollBarEnabled(boolean)
6038 */
6039 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006040 final ScrollabilityCache scrollCache = mScrollCache;
6041
6042 if (scrollCache == null || !scrollCache.fadeScrollBars) {
6043 return false;
6044 }
6045
6046 if (scrollCache.scrollBar == null) {
6047 scrollCache.scrollBar = new ScrollBarDrawable();
6048 }
6049
6050 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6051
Mike Cleron290947b2009-09-29 18:34:32 -07006052 if (invalidate) {
6053 // Invalidate to show the scrollbars
6054 invalidate();
6055 }
Mike Cleronf116bf82009-09-27 19:14:12 -07006056
6057 if (scrollCache.state == ScrollabilityCache.OFF) {
6058 // FIXME: this is copied from WindowManagerService.
6059 // We should get this value from the system when it
6060 // is possible to do so.
6061 final int KEY_REPEAT_FIRST_DELAY = 750;
6062 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6063 }
6064
6065 // Tell mScrollCache when we should start fading. This may
6066 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07006067 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07006068 scrollCache.fadeStartTime = fadeStartTime;
6069 scrollCache.state = ScrollabilityCache.ON;
6070
6071 // Schedule our fader to run, unscheduling any old ones first
6072 if (mAttachInfo != null) {
6073 mAttachInfo.mHandler.removeCallbacks(scrollCache);
6074 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6075 }
6076
6077 return true;
6078 }
6079
6080 return false;
6081 }
6082
6083 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006084 * Mark the the area defined by dirty as needing to be drawn. If the view is
6085 * visible, {@link #onDraw} will be called at some point in the future.
6086 * This must be called from a UI thread. To call from a non-UI thread, call
6087 * {@link #postInvalidate()}.
6088 *
6089 * WARNING: This method is destructive to dirty.
6090 * @param dirty the rectangle representing the bounds of the dirty region
6091 */
6092 public void invalidate(Rect dirty) {
6093 if (ViewDebug.TRACE_HIERARCHY) {
6094 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6095 }
6096
6097 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6098 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6099 final ViewParent p = mParent;
6100 final AttachInfo ai = mAttachInfo;
6101 if (p != null && ai != null) {
6102 final int scrollX = mScrollX;
6103 final int scrollY = mScrollY;
6104 final Rect r = ai.mTmpInvalRect;
6105 r.set(dirty.left - scrollX, dirty.top - scrollY,
6106 dirty.right - scrollX, dirty.bottom - scrollY);
6107 mParent.invalidateChild(this, r);
6108 }
6109 }
6110 }
6111
6112 /**
6113 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6114 * The coordinates of the dirty rect are relative to the view.
6115 * If the view is visible, {@link #onDraw} will be called at some point
6116 * in the future. This must be called from a UI thread. To call
6117 * from a non-UI thread, call {@link #postInvalidate()}.
6118 * @param l the left position of the dirty region
6119 * @param t the top position of the dirty region
6120 * @param r the right position of the dirty region
6121 * @param b the bottom position of the dirty region
6122 */
6123 public void invalidate(int l, int t, int r, int b) {
6124 if (ViewDebug.TRACE_HIERARCHY) {
6125 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6126 }
6127
6128 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6129 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6130 final ViewParent p = mParent;
6131 final AttachInfo ai = mAttachInfo;
6132 if (p != null && ai != null && l < r && t < b) {
6133 final int scrollX = mScrollX;
6134 final int scrollY = mScrollY;
6135 final Rect tmpr = ai.mTmpInvalRect;
6136 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6137 p.invalidateChild(this, tmpr);
6138 }
6139 }
6140 }
6141
6142 /**
6143 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6144 * be called at some point in the future. This must be called from a
6145 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6146 */
6147 public void invalidate() {
6148 if (ViewDebug.TRACE_HIERARCHY) {
6149 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6150 }
6151
6152 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
6153 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
6154 final ViewParent p = mParent;
6155 final AttachInfo ai = mAttachInfo;
6156 if (p != null && ai != null) {
6157 final Rect r = ai.mTmpInvalRect;
6158 r.set(0, 0, mRight - mLeft, mBottom - mTop);
6159 // Don't call invalidate -- we don't want to internally scroll
6160 // our own bounds
6161 p.invalidateChild(this, r);
6162 }
6163 }
6164 }
6165
6166 /**
Romain Guy24443ea2009-05-11 11:56:30 -07006167 * Indicates whether this View is opaque. An opaque View guarantees that it will
6168 * draw all the pixels overlapping its bounds using a fully opaque color.
6169 *
6170 * Subclasses of View should override this method whenever possible to indicate
6171 * whether an instance is opaque. Opaque Views are treated in a special way by
6172 * the View hierarchy, possibly allowing it to perform optimizations during
6173 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07006174 *
Romain Guy24443ea2009-05-11 11:56:30 -07006175 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07006176 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07006177 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy24443ea2009-05-11 11:56:30 -07006178 public boolean isOpaque() {
Romain Guy8f1344f52009-05-15 16:03:59 -07006179 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK;
6180 }
6181
6182 private void computeOpaqueFlags() {
6183 // Opaque if:
6184 // - Has a background
6185 // - Background is opaque
6186 // - Doesn't have scrollbars or scrollbars are inside overlay
6187
6188 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6189 mPrivateFlags |= OPAQUE_BACKGROUND;
6190 } else {
6191 mPrivateFlags &= ~OPAQUE_BACKGROUND;
6192 }
6193
6194 final int flags = mViewFlags;
6195 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6196 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6197 mPrivateFlags |= OPAQUE_SCROLLBARS;
6198 } else {
6199 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6200 }
6201 }
6202
6203 /**
6204 * @hide
6205 */
6206 protected boolean hasOpaqueScrollbars() {
6207 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07006208 }
6209
6210 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 * @return A handler associated with the thread running the View. This
6212 * handler can be used to pump events in the UI events queue.
6213 */
6214 public Handler getHandler() {
6215 if (mAttachInfo != null) {
6216 return mAttachInfo.mHandler;
6217 }
6218 return null;
6219 }
6220
6221 /**
6222 * Causes the Runnable to be added to the message queue.
6223 * The runnable will be run on the user interface thread.
6224 *
6225 * @param action The Runnable that will be executed.
6226 *
6227 * @return Returns true if the Runnable was successfully placed in to the
6228 * message queue. Returns false on failure, usually because the
6229 * looper processing the message queue is exiting.
6230 */
6231 public boolean post(Runnable action) {
6232 Handler handler;
6233 if (mAttachInfo != null) {
6234 handler = mAttachInfo.mHandler;
6235 } else {
6236 // Assume that post will succeed later
6237 ViewRoot.getRunQueue().post(action);
6238 return true;
6239 }
6240
6241 return handler.post(action);
6242 }
6243
6244 /**
6245 * Causes the Runnable to be added to the message queue, to be run
6246 * after the specified amount of time elapses.
6247 * The runnable will be run on the user interface thread.
6248 *
6249 * @param action The Runnable that will be executed.
6250 * @param delayMillis The delay (in milliseconds) until the Runnable
6251 * will be executed.
6252 *
6253 * @return true if the Runnable was successfully placed in to the
6254 * message queue. Returns false on failure, usually because the
6255 * looper processing the message queue is exiting. Note that a
6256 * result of true does not mean the Runnable will be processed --
6257 * if the looper is quit before the delivery time of the message
6258 * occurs then the message will be dropped.
6259 */
6260 public boolean postDelayed(Runnable action, long delayMillis) {
6261 Handler handler;
6262 if (mAttachInfo != null) {
6263 handler = mAttachInfo.mHandler;
6264 } else {
6265 // Assume that post will succeed later
6266 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6267 return true;
6268 }
6269
6270 return handler.postDelayed(action, delayMillis);
6271 }
6272
6273 /**
6274 * Removes the specified Runnable from the message queue.
6275 *
6276 * @param action The Runnable to remove from the message handling queue
6277 *
6278 * @return true if this view could ask the Handler to remove the Runnable,
6279 * false otherwise. When the returned value is true, the Runnable
6280 * may or may not have been actually removed from the message queue
6281 * (for instance, if the Runnable was not in the queue already.)
6282 */
6283 public boolean removeCallbacks(Runnable action) {
6284 Handler handler;
6285 if (mAttachInfo != null) {
6286 handler = mAttachInfo.mHandler;
6287 } else {
6288 // Assume that post will succeed later
6289 ViewRoot.getRunQueue().removeCallbacks(action);
6290 return true;
6291 }
6292
6293 handler.removeCallbacks(action);
6294 return true;
6295 }
6296
6297 /**
6298 * Cause an invalidate to happen on a subsequent cycle through the event loop.
6299 * Use this to invalidate the View from a non-UI thread.
6300 *
6301 * @see #invalidate()
6302 */
6303 public void postInvalidate() {
6304 postInvalidateDelayed(0);
6305 }
6306
6307 /**
6308 * Cause an invalidate of the specified area to happen on a subsequent cycle
6309 * through the event loop. Use this to invalidate the View from a non-UI thread.
6310 *
6311 * @param left The left coordinate of the rectangle to invalidate.
6312 * @param top The top coordinate of the rectangle to invalidate.
6313 * @param right The right coordinate of the rectangle to invalidate.
6314 * @param bottom The bottom coordinate of the rectangle to invalidate.
6315 *
6316 * @see #invalidate(int, int, int, int)
6317 * @see #invalidate(Rect)
6318 */
6319 public void postInvalidate(int left, int top, int right, int bottom) {
6320 postInvalidateDelayed(0, left, top, right, bottom);
6321 }
6322
6323 /**
6324 * Cause an invalidate to happen on a subsequent cycle through the event
6325 * loop. Waits for the specified amount of time.
6326 *
6327 * @param delayMilliseconds the duration in milliseconds to delay the
6328 * invalidation by
6329 */
6330 public void postInvalidateDelayed(long delayMilliseconds) {
6331 // We try only with the AttachInfo because there's no point in invalidating
6332 // if we are not attached to our window
6333 if (mAttachInfo != null) {
6334 Message msg = Message.obtain();
6335 msg.what = AttachInfo.INVALIDATE_MSG;
6336 msg.obj = this;
6337 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6338 }
6339 }
6340
6341 /**
6342 * Cause an invalidate of the specified area to happen on a subsequent cycle
6343 * through the event loop. Waits for the specified amount of time.
6344 *
6345 * @param delayMilliseconds the duration in milliseconds to delay the
6346 * invalidation by
6347 * @param left The left coordinate of the rectangle to invalidate.
6348 * @param top The top coordinate of the rectangle to invalidate.
6349 * @param right The right coordinate of the rectangle to invalidate.
6350 * @param bottom The bottom coordinate of the rectangle to invalidate.
6351 */
6352 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6353 int right, int bottom) {
6354
6355 // We try only with the AttachInfo because there's no point in invalidating
6356 // if we are not attached to our window
6357 if (mAttachInfo != null) {
6358 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6359 info.target = this;
6360 info.left = left;
6361 info.top = top;
6362 info.right = right;
6363 info.bottom = bottom;
6364
6365 final Message msg = Message.obtain();
6366 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
6367 msg.obj = info;
6368 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6369 }
6370 }
6371
6372 /**
6373 * Called by a parent to request that a child update its values for mScrollX
6374 * and mScrollY if necessary. This will typically be done if the child is
6375 * animating a scroll using a {@link android.widget.Scroller Scroller}
6376 * object.
6377 */
6378 public void computeScroll() {
6379 }
6380
6381 /**
6382 * <p>Indicate whether the horizontal edges are faded when the view is
6383 * scrolled horizontally.</p>
6384 *
6385 * @return true if the horizontal edges should are faded on scroll, false
6386 * otherwise
6387 *
6388 * @see #setHorizontalFadingEdgeEnabled(boolean)
6389 * @attr ref android.R.styleable#View_fadingEdge
6390 */
6391 public boolean isHorizontalFadingEdgeEnabled() {
6392 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
6393 }
6394
6395 /**
6396 * <p>Define whether the horizontal edges should be faded when this view
6397 * is scrolled horizontally.</p>
6398 *
6399 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
6400 * be faded when the view is scrolled
6401 * horizontally
6402 *
6403 * @see #isHorizontalFadingEdgeEnabled()
6404 * @attr ref android.R.styleable#View_fadingEdge
6405 */
6406 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
6407 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
6408 if (horizontalFadingEdgeEnabled) {
6409 initScrollCache();
6410 }
6411
6412 mViewFlags ^= FADING_EDGE_HORIZONTAL;
6413 }
6414 }
6415
6416 /**
6417 * <p>Indicate whether the vertical edges are faded when the view is
6418 * scrolled horizontally.</p>
6419 *
6420 * @return true if the vertical edges should are faded on scroll, false
6421 * otherwise
6422 *
6423 * @see #setVerticalFadingEdgeEnabled(boolean)
6424 * @attr ref android.R.styleable#View_fadingEdge
6425 */
6426 public boolean isVerticalFadingEdgeEnabled() {
6427 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
6428 }
6429
6430 /**
6431 * <p>Define whether the vertical edges should be faded when this view
6432 * is scrolled vertically.</p>
6433 *
6434 * @param verticalFadingEdgeEnabled true if the vertical edges should
6435 * be faded when the view is scrolled
6436 * vertically
6437 *
6438 * @see #isVerticalFadingEdgeEnabled()
6439 * @attr ref android.R.styleable#View_fadingEdge
6440 */
6441 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
6442 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
6443 if (verticalFadingEdgeEnabled) {
6444 initScrollCache();
6445 }
6446
6447 mViewFlags ^= FADING_EDGE_VERTICAL;
6448 }
6449 }
6450
6451 /**
6452 * Returns the strength, or intensity, of the top faded edge. The strength is
6453 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6454 * returns 0.0 or 1.0 but no value in between.
6455 *
6456 * Subclasses should override this method to provide a smoother fade transition
6457 * when scrolling occurs.
6458 *
6459 * @return the intensity of the top fade as a float between 0.0f and 1.0f
6460 */
6461 protected float getTopFadingEdgeStrength() {
6462 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
6463 }
6464
6465 /**
6466 * Returns the strength, or intensity, of the bottom faded edge. The strength is
6467 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6468 * returns 0.0 or 1.0 but no value in between.
6469 *
6470 * Subclasses should override this method to provide a smoother fade transition
6471 * when scrolling occurs.
6472 *
6473 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
6474 */
6475 protected float getBottomFadingEdgeStrength() {
6476 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
6477 computeVerticalScrollRange() ? 1.0f : 0.0f;
6478 }
6479
6480 /**
6481 * Returns the strength, or intensity, of the left faded edge. The strength is
6482 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6483 * returns 0.0 or 1.0 but no value in between.
6484 *
6485 * Subclasses should override this method to provide a smoother fade transition
6486 * when scrolling occurs.
6487 *
6488 * @return the intensity of the left fade as a float between 0.0f and 1.0f
6489 */
6490 protected float getLeftFadingEdgeStrength() {
6491 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
6492 }
6493
6494 /**
6495 * Returns the strength, or intensity, of the right faded edge. The strength is
6496 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
6497 * returns 0.0 or 1.0 but no value in between.
6498 *
6499 * Subclasses should override this method to provide a smoother fade transition
6500 * when scrolling occurs.
6501 *
6502 * @return the intensity of the right fade as a float between 0.0f and 1.0f
6503 */
6504 protected float getRightFadingEdgeStrength() {
6505 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
6506 computeHorizontalScrollRange() ? 1.0f : 0.0f;
6507 }
6508
6509 /**
6510 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
6511 * scrollbar is not drawn by default.</p>
6512 *
6513 * @return true if the horizontal scrollbar should be painted, false
6514 * otherwise
6515 *
6516 * @see #setHorizontalScrollBarEnabled(boolean)
6517 */
6518 public boolean isHorizontalScrollBarEnabled() {
6519 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6520 }
6521
6522 /**
6523 * <p>Define whether the horizontal scrollbar should be drawn or not. The
6524 * scrollbar is not drawn by default.</p>
6525 *
6526 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
6527 * be painted
6528 *
6529 * @see #isHorizontalScrollBarEnabled()
6530 */
6531 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
6532 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
6533 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006534 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 recomputePadding();
6536 }
6537 }
6538
6539 /**
6540 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
6541 * scrollbar is not drawn by default.</p>
6542 *
6543 * @return true if the vertical scrollbar should be painted, false
6544 * otherwise
6545 *
6546 * @see #setVerticalScrollBarEnabled(boolean)
6547 */
6548 public boolean isVerticalScrollBarEnabled() {
6549 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
6550 }
6551
6552 /**
6553 * <p>Define whether the vertical scrollbar should be drawn or not. The
6554 * scrollbar is not drawn by default.</p>
6555 *
6556 * @param verticalScrollBarEnabled true if the vertical scrollbar should
6557 * be painted
6558 *
6559 * @see #isVerticalScrollBarEnabled()
6560 */
6561 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
6562 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
6563 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07006564 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006565 recomputePadding();
6566 }
6567 }
6568
6569 private void recomputePadding() {
6570 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
6571 }
Mike Cleronfe81d382009-09-28 14:22:16 -07006572
6573 /**
6574 * Define whether scrollbars will fade when the view is not scrolling.
6575 *
6576 * @param fadeScrollbars wheter to enable fading
6577 *
6578 */
6579 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
6580 initScrollCache();
6581 final ScrollabilityCache scrollabilityCache = mScrollCache;
6582 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07006583 if (fadeScrollbars) {
6584 scrollabilityCache.state = ScrollabilityCache.OFF;
6585 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07006586 scrollabilityCache.state = ScrollabilityCache.ON;
6587 }
6588 }
6589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07006591 *
6592 * Returns true if scrollbars will fade when this view is not scrolling
6593 *
6594 * @return true if scrollbar fading is enabled
6595 */
6596 public boolean isScrollbarFadingEnabled() {
6597 return mScrollCache != null && mScrollCache.fadeScrollBars;
6598 }
6599
6600 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006601 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
6602 * inset. When inset, they add to the padding of the view. And the scrollbars
6603 * can be drawn inside the padding area or on the edge of the view. For example,
6604 * if a view has a background drawable and you want to draw the scrollbars
6605 * inside the padding specified by the drawable, you can use
6606 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
6607 * appear at the edge of the view, ignoring the padding, then you can use
6608 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
6609 * @param style the style of the scrollbars. Should be one of
6610 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
6611 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
6612 * @see #SCROLLBARS_INSIDE_OVERLAY
6613 * @see #SCROLLBARS_INSIDE_INSET
6614 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6615 * @see #SCROLLBARS_OUTSIDE_INSET
6616 */
6617 public void setScrollBarStyle(int style) {
6618 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
6619 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07006620 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621 recomputePadding();
6622 }
6623 }
6624
6625 /**
6626 * <p>Returns the current scrollbar style.</p>
6627 * @return the current scrollbar style
6628 * @see #SCROLLBARS_INSIDE_OVERLAY
6629 * @see #SCROLLBARS_INSIDE_INSET
6630 * @see #SCROLLBARS_OUTSIDE_OVERLAY
6631 * @see #SCROLLBARS_OUTSIDE_INSET
6632 */
6633 public int getScrollBarStyle() {
6634 return mViewFlags & SCROLLBARS_STYLE_MASK;
6635 }
6636
6637 /**
6638 * <p>Compute the horizontal range that the horizontal scrollbar
6639 * represents.</p>
6640 *
6641 * <p>The range is expressed in arbitrary units that must be the same as the
6642 * units used by {@link #computeHorizontalScrollExtent()} and
6643 * {@link #computeHorizontalScrollOffset()}.</p>
6644 *
6645 * <p>The default range is the drawing width of this view.</p>
6646 *
6647 * @return the total horizontal range represented by the horizontal
6648 * scrollbar
6649 *
6650 * @see #computeHorizontalScrollExtent()
6651 * @see #computeHorizontalScrollOffset()
6652 * @see android.widget.ScrollBarDrawable
6653 */
6654 protected int computeHorizontalScrollRange() {
6655 return getWidth();
6656 }
6657
6658 /**
6659 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
6660 * within the horizontal range. This value is used to compute the position
6661 * of the thumb within the scrollbar's track.</p>
6662 *
6663 * <p>The range is expressed in arbitrary units that must be the same as the
6664 * units used by {@link #computeHorizontalScrollRange()} and
6665 * {@link #computeHorizontalScrollExtent()}.</p>
6666 *
6667 * <p>The default offset is the scroll offset of this view.</p>
6668 *
6669 * @return the horizontal offset of the scrollbar's thumb
6670 *
6671 * @see #computeHorizontalScrollRange()
6672 * @see #computeHorizontalScrollExtent()
6673 * @see android.widget.ScrollBarDrawable
6674 */
6675 protected int computeHorizontalScrollOffset() {
6676 return mScrollX;
6677 }
6678
6679 /**
6680 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
6681 * within the horizontal range. This value is used to compute the length
6682 * of the thumb within the scrollbar's track.</p>
6683 *
6684 * <p>The range is expressed in arbitrary units that must be the same as the
6685 * units used by {@link #computeHorizontalScrollRange()} and
6686 * {@link #computeHorizontalScrollOffset()}.</p>
6687 *
6688 * <p>The default extent is the drawing width of this view.</p>
6689 *
6690 * @return the horizontal extent of the scrollbar's thumb
6691 *
6692 * @see #computeHorizontalScrollRange()
6693 * @see #computeHorizontalScrollOffset()
6694 * @see android.widget.ScrollBarDrawable
6695 */
6696 protected int computeHorizontalScrollExtent() {
6697 return getWidth();
6698 }
6699
6700 /**
6701 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
6702 *
6703 * <p>The range is expressed in arbitrary units that must be the same as the
6704 * units used by {@link #computeVerticalScrollExtent()} and
6705 * {@link #computeVerticalScrollOffset()}.</p>
6706 *
6707 * @return the total vertical range represented by the vertical scrollbar
6708 *
6709 * <p>The default range is the drawing height of this view.</p>
6710 *
6711 * @see #computeVerticalScrollExtent()
6712 * @see #computeVerticalScrollOffset()
6713 * @see android.widget.ScrollBarDrawable
6714 */
6715 protected int computeVerticalScrollRange() {
6716 return getHeight();
6717 }
6718
6719 /**
6720 * <p>Compute the vertical offset of the vertical scrollbar's thumb
6721 * within the horizontal range. This value is used to compute the position
6722 * of the thumb within the scrollbar's track.</p>
6723 *
6724 * <p>The range is expressed in arbitrary units that must be the same as the
6725 * units used by {@link #computeVerticalScrollRange()} and
6726 * {@link #computeVerticalScrollExtent()}.</p>
6727 *
6728 * <p>The default offset is the scroll offset of this view.</p>
6729 *
6730 * @return the vertical offset of the scrollbar's thumb
6731 *
6732 * @see #computeVerticalScrollRange()
6733 * @see #computeVerticalScrollExtent()
6734 * @see android.widget.ScrollBarDrawable
6735 */
6736 protected int computeVerticalScrollOffset() {
6737 return mScrollY;
6738 }
6739
6740 /**
6741 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
6742 * within the vertical range. This value is used to compute the length
6743 * of the thumb within the scrollbar's track.</p>
6744 *
6745 * <p>The range is expressed in arbitrary units that must be the same as the
Gilles Debunne52964242010-02-24 11:05:19 -08006746 * units used by {@link #computeVerticalScrollRange()} and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 * {@link #computeVerticalScrollOffset()}.</p>
6748 *
6749 * <p>The default extent is the drawing height of this view.</p>
6750 *
6751 * @return the vertical extent of the scrollbar's thumb
6752 *
6753 * @see #computeVerticalScrollRange()
6754 * @see #computeVerticalScrollOffset()
6755 * @see android.widget.ScrollBarDrawable
6756 */
6757 protected int computeVerticalScrollExtent() {
6758 return getHeight();
6759 }
6760
6761 /**
6762 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
6763 * scrollbars are painted only if they have been awakened first.</p>
6764 *
6765 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07006766 *
6767 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08006769 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006770 // scrollbars are drawn only when the animation is running
6771 final ScrollabilityCache cache = mScrollCache;
6772 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006773
6774 int state = cache.state;
6775
6776 if (state == ScrollabilityCache.OFF) {
6777 return;
6778 }
6779
6780 boolean invalidate = false;
6781
6782 if (state == ScrollabilityCache.FADING) {
6783 // We're fading -- get our fade interpolation
6784 if (cache.interpolatorValues == null) {
6785 cache.interpolatorValues = new float[1];
6786 }
6787
6788 float[] values = cache.interpolatorValues;
6789
6790 // Stops the animation if we're done
6791 if (cache.scrollBarInterpolator.timeToValues(values) ==
6792 Interpolator.Result.FREEZE_END) {
6793 cache.state = ScrollabilityCache.OFF;
6794 } else {
6795 cache.scrollBar.setAlpha(Math.round(values[0]));
6796 }
6797
6798 // This will make the scroll bars inval themselves after
6799 // drawing. We only want this when we're fading so that
6800 // we prevent excessive redraws
6801 invalidate = true;
6802 } else {
6803 // We're just on -- but we may have been fading before so
6804 // reset alpha
6805 cache.scrollBar.setAlpha(255);
6806 }
6807
6808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 final int viewFlags = mViewFlags;
6810
6811 final boolean drawHorizontalScrollBar =
6812 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
6813 final boolean drawVerticalScrollBar =
6814 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
6815 && !isVerticalScrollBarHidden();
6816
6817 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
6818 final int width = mRight - mLeft;
6819 final int height = mBottom - mTop;
6820
6821 final ScrollBarDrawable scrollBar = cache.scrollBar;
6822 int size = scrollBar.getSize(false);
6823 if (size <= 0) {
6824 size = cache.scrollBarSize;
6825 }
6826
Mike Reede8853fc2009-09-04 14:01:48 -04006827 final int scrollX = mScrollX;
6828 final int scrollY = mScrollY;
6829 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
6830
Mike Cleronf116bf82009-09-27 19:14:12 -07006831 int left, top, right, bottom;
6832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006833 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07006834 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04006835 computeHorizontalScrollOffset(),
6836 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04006837 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07006838 getVerticalScrollbarWidth() : 0;
6839 top = scrollY + height - size - (mUserPaddingBottom & inside);
6840 left = scrollX + (mPaddingLeft & inside);
6841 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
6842 bottom = top + size;
6843 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
6844 if (invalidate) {
6845 invalidate(left, top, right, bottom);
6846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 }
6848
6849 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04006850 scrollBar.setParameters(computeVerticalScrollRange(),
6851 computeVerticalScrollOffset(),
6852 computeVerticalScrollExtent(), true);
6853 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07006854 left = scrollX + width - size - (mUserPaddingRight & inside);
6855 top = scrollY + (mPaddingTop & inside);
6856 right = left + size;
6857 bottom = scrollY + height - (mUserPaddingBottom & inside);
6858 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
6859 if (invalidate) {
6860 invalidate(left, top, right, bottom);
6861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006862 }
6863 }
6864 }
6865 }
Romain Guy8506ab42009-06-11 17:35:47 -07006866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006867 /**
Romain Guy8506ab42009-06-11 17:35:47 -07006868 * 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 -08006869 * FastScroller is visible.
6870 * @return whether to temporarily hide the vertical scrollbar
6871 * @hide
6872 */
6873 protected boolean isVerticalScrollBarHidden() {
6874 return false;
6875 }
6876
6877 /**
6878 * <p>Draw the horizontal scrollbar if
6879 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
6880 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006881 * @param canvas the canvas on which to draw the scrollbar
6882 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006883 *
6884 * @see #isHorizontalScrollBarEnabled()
6885 * @see #computeHorizontalScrollRange()
6886 * @see #computeHorizontalScrollExtent()
6887 * @see #computeHorizontalScrollOffset()
6888 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07006889 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006890 */
Romain Guy8fb95422010-08-17 18:38:51 -07006891 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
6892 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006893 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006894 scrollBar.draw(canvas);
6895 }
Mike Reede8853fc2009-09-04 14:01:48 -04006896
Mike Reed4d6fe5f2009-09-03 13:29:05 -04006897 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006898 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
6899 * returns true.</p>
6900 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006901 * @param canvas the canvas on which to draw the scrollbar
6902 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 *
6904 * @see #isVerticalScrollBarEnabled()
6905 * @see #computeVerticalScrollRange()
6906 * @see #computeVerticalScrollExtent()
6907 * @see #computeVerticalScrollOffset()
6908 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04006909 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006910 */
Romain Guy8fb95422010-08-17 18:38:51 -07006911 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
6912 int l, int t, int r, int b) {
Mike Reede8853fc2009-09-04 14:01:48 -04006913 scrollBar.setBounds(l, t, r, b);
6914 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006915 }
6916
6917 /**
6918 * Implement this to do your drawing.
6919 *
6920 * @param canvas the canvas on which the background will be drawn
6921 */
6922 protected void onDraw(Canvas canvas) {
6923 }
6924
6925 /*
6926 * Caller is responsible for calling requestLayout if necessary.
6927 * (This allows addViewInLayout to not request a new layout.)
6928 */
6929 void assignParent(ViewParent parent) {
6930 if (mParent == null) {
6931 mParent = parent;
6932 } else if (parent == null) {
6933 mParent = null;
6934 } else {
6935 throw new RuntimeException("view " + this + " being added, but"
6936 + " it already has a parent");
6937 }
6938 }
6939
6940 /**
6941 * This is called when the view is attached to a window. At this point it
6942 * has a Surface and will start drawing. Note that this function is
6943 * guaranteed to be called before {@link #onDraw}, however it may be called
6944 * any time before the first onDraw -- including before or after
6945 * {@link #onMeasure}.
6946 *
6947 * @see #onDetachedFromWindow()
6948 */
6949 protected void onAttachedToWindow() {
6950 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
6951 mParent.requestTransparentRegion(this);
6952 }
Adam Powell8568c3a2010-04-19 14:26:11 -07006953 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
6954 initialAwakenScrollBars();
6955 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
6956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006957 }
6958
6959 /**
6960 * This is called when the view is detached from a window. At this point it
6961 * no longer has a surface for drawing.
6962 *
6963 * @see #onAttachedToWindow()
6964 */
6965 protected void onDetachedFromWindow() {
Romain Guy8afa5152010-02-26 11:56:30 -08006966 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
Romain Guya440b002010-02-24 15:57:54 -08006967 removeUnsetPressCallback();
Maryam Garrett1549dd12009-12-15 16:06:36 -05006968 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 destroyDrawingCache();
6970 }
6971
6972 /**
6973 * @return The number of times this view has been attached to a window
6974 */
6975 protected int getWindowAttachCount() {
6976 return mWindowAttachCount;
6977 }
6978
6979 /**
6980 * Retrieve a unique token identifying the window this view is attached to.
6981 * @return Return the window's token for use in
6982 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
6983 */
6984 public IBinder getWindowToken() {
6985 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
6986 }
6987
6988 /**
6989 * Retrieve a unique token identifying the top-level "real" window of
6990 * the window that this view is attached to. That is, this is like
6991 * {@link #getWindowToken}, except if the window this view in is a panel
6992 * window (attached to another containing window), then the token of
6993 * the containing window is returned instead.
6994 *
6995 * @return Returns the associated window token, either
6996 * {@link #getWindowToken()} or the containing window's token.
6997 */
6998 public IBinder getApplicationWindowToken() {
6999 AttachInfo ai = mAttachInfo;
7000 if (ai != null) {
7001 IBinder appWindowToken = ai.mPanelParentWindowToken;
7002 if (appWindowToken == null) {
7003 appWindowToken = ai.mWindowToken;
7004 }
7005 return appWindowToken;
7006 }
7007 return null;
7008 }
7009
7010 /**
7011 * Retrieve private session object this view hierarchy is using to
7012 * communicate with the window manager.
7013 * @return the session object to communicate with the window manager
7014 */
7015 /*package*/ IWindowSession getWindowSession() {
7016 return mAttachInfo != null ? mAttachInfo.mSession : null;
7017 }
7018
7019 /**
7020 * @param info the {@link android.view.View.AttachInfo} to associated with
7021 * this view
7022 */
7023 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7024 //System.out.println("Attached! " + this);
7025 mAttachInfo = info;
7026 mWindowAttachCount++;
7027 if (mFloatingTreeObserver != null) {
7028 info.mTreeObserver.merge(mFloatingTreeObserver);
7029 mFloatingTreeObserver = null;
7030 }
7031 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7032 mAttachInfo.mScrollContainers.add(this);
7033 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7034 }
7035 performCollectViewAttributes(visibility);
7036 onAttachedToWindow();
7037 int vis = info.mWindowVisibility;
7038 if (vis != GONE) {
7039 onWindowVisibilityChanged(vis);
7040 }
7041 }
7042
7043 void dispatchDetachedFromWindow() {
7044 //System.out.println("Detached! " + this);
7045 AttachInfo info = mAttachInfo;
7046 if (info != null) {
7047 int vis = info.mWindowVisibility;
7048 if (vis != GONE) {
7049 onWindowVisibilityChanged(GONE);
7050 }
7051 }
7052
7053 onDetachedFromWindow();
7054 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7055 mAttachInfo.mScrollContainers.remove(this);
7056 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7057 }
7058 mAttachInfo = null;
7059 }
7060
7061 /**
7062 * Store this view hierarchy's frozen state into the given container.
7063 *
7064 * @param container The SparseArray in which to save the view's state.
7065 *
7066 * @see #restoreHierarchyState
7067 * @see #dispatchSaveInstanceState
7068 * @see #onSaveInstanceState
7069 */
7070 public void saveHierarchyState(SparseArray<Parcelable> container) {
7071 dispatchSaveInstanceState(container);
7072 }
7073
7074 /**
7075 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7076 * May be overridden to modify how freezing happens to a view's children; for example, some
7077 * views may want to not store state for their children.
7078 *
7079 * @param container The SparseArray in which to save the view's state.
7080 *
7081 * @see #dispatchRestoreInstanceState
7082 * @see #saveHierarchyState
7083 * @see #onSaveInstanceState
7084 */
7085 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7086 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7087 mPrivateFlags &= ~SAVE_STATE_CALLED;
7088 Parcelable state = onSaveInstanceState();
7089 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7090 throw new IllegalStateException(
7091 "Derived class did not call super.onSaveInstanceState()");
7092 }
7093 if (state != null) {
7094 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7095 // + ": " + state);
7096 container.put(mID, state);
7097 }
7098 }
7099 }
7100
7101 /**
7102 * Hook allowing a view to generate a representation of its internal state
7103 * that can later be used to create a new instance with that same state.
7104 * This state should only contain information that is not persistent or can
7105 * not be reconstructed later. For example, you will never store your
7106 * current position on screen because that will be computed again when a
7107 * new instance of the view is placed in its view hierarchy.
7108 * <p>
7109 * Some examples of things you may store here: the current cursor position
7110 * in a text view (but usually not the text itself since that is stored in a
7111 * content provider or other persistent storage), the currently selected
7112 * item in a list view.
7113 *
7114 * @return Returns a Parcelable object containing the view's current dynamic
7115 * state, or null if there is nothing interesting to save. The
7116 * default implementation returns null.
7117 * @see #onRestoreInstanceState
7118 * @see #saveHierarchyState
7119 * @see #dispatchSaveInstanceState
7120 * @see #setSaveEnabled(boolean)
7121 */
7122 protected Parcelable onSaveInstanceState() {
7123 mPrivateFlags |= SAVE_STATE_CALLED;
7124 return BaseSavedState.EMPTY_STATE;
7125 }
7126
7127 /**
7128 * Restore this view hierarchy's frozen state from the given container.
7129 *
7130 * @param container The SparseArray which holds previously frozen states.
7131 *
7132 * @see #saveHierarchyState
7133 * @see #dispatchRestoreInstanceState
7134 * @see #onRestoreInstanceState
7135 */
7136 public void restoreHierarchyState(SparseArray<Parcelable> container) {
7137 dispatchRestoreInstanceState(container);
7138 }
7139
7140 /**
7141 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7142 * children. May be overridden to modify how restoreing happens to a view's children; for
7143 * example, some views may want to not store state for their children.
7144 *
7145 * @param container The SparseArray which holds previously saved state.
7146 *
7147 * @see #dispatchSaveInstanceState
7148 * @see #restoreHierarchyState
7149 * @see #onRestoreInstanceState
7150 */
7151 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7152 if (mID != NO_ID) {
7153 Parcelable state = container.get(mID);
7154 if (state != null) {
7155 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7156 // + ": " + state);
7157 mPrivateFlags &= ~SAVE_STATE_CALLED;
7158 onRestoreInstanceState(state);
7159 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7160 throw new IllegalStateException(
7161 "Derived class did not call super.onRestoreInstanceState()");
7162 }
7163 }
7164 }
7165 }
7166
7167 /**
7168 * Hook allowing a view to re-apply a representation of its internal state that had previously
7169 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7170 * null state.
7171 *
7172 * @param state The frozen state that had previously been returned by
7173 * {@link #onSaveInstanceState}.
7174 *
7175 * @see #onSaveInstanceState
7176 * @see #restoreHierarchyState
7177 * @see #dispatchRestoreInstanceState
7178 */
7179 protected void onRestoreInstanceState(Parcelable state) {
7180 mPrivateFlags |= SAVE_STATE_CALLED;
7181 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08007182 throw new IllegalArgumentException("Wrong state class, expecting View State but "
7183 + "received " + state.getClass().toString() + " instead. This usually happens "
7184 + "when two views of different type have the same id in the same hierarchy. "
7185 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7186 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 }
7188 }
7189
7190 /**
7191 * <p>Return the time at which the drawing of the view hierarchy started.</p>
7192 *
7193 * @return the drawing start time in milliseconds
7194 */
7195 public long getDrawingTime() {
7196 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7197 }
7198
7199 /**
7200 * <p>Enables or disables the duplication of the parent's state into this view. When
7201 * duplication is enabled, this view gets its drawable state from its parent rather
7202 * than from its own internal properties.</p>
7203 *
7204 * <p>Note: in the current implementation, setting this property to true after the
7205 * view was added to a ViewGroup might have no effect at all. This property should
7206 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7207 *
7208 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7209 * property is enabled, an exception will be thrown.</p>
7210 *
7211 * @param enabled True to enable duplication of the parent's drawable state, false
7212 * to disable it.
7213 *
7214 * @see #getDrawableState()
7215 * @see #isDuplicateParentStateEnabled()
7216 */
7217 public void setDuplicateParentStateEnabled(boolean enabled) {
7218 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7219 }
7220
7221 /**
7222 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7223 *
7224 * @return True if this view's drawable state is duplicated from the parent,
7225 * false otherwise
7226 *
7227 * @see #getDrawableState()
7228 * @see #setDuplicateParentStateEnabled(boolean)
7229 */
7230 public boolean isDuplicateParentStateEnabled() {
7231 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7232 }
7233
7234 /**
7235 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
7236 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
7237 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
7238 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
7239 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
7240 * null.</p>
7241 *
7242 * @param enabled true to enable the drawing cache, false otherwise
7243 *
7244 * @see #isDrawingCacheEnabled()
7245 * @see #getDrawingCache()
7246 * @see #buildDrawingCache()
7247 */
7248 public void setDrawingCacheEnabled(boolean enabled) {
7249 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
7250 }
7251
7252 /**
7253 * <p>Indicates whether the drawing cache is enabled for this view.</p>
7254 *
7255 * @return true if the drawing cache is enabled
7256 *
7257 * @see #setDrawingCacheEnabled(boolean)
7258 * @see #getDrawingCache()
7259 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07007260 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007261 public boolean isDrawingCacheEnabled() {
7262 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
7263 }
7264
7265 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007266 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
7267 *
7268 * @return A non-scaled bitmap representing this view or null if cache is disabled.
7269 *
7270 * @see #getDrawingCache(boolean)
7271 */
7272 public Bitmap getDrawingCache() {
7273 return getDrawingCache(false);
7274 }
7275
7276 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007277 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
7278 * is null when caching is disabled. If caching is enabled and the cache is not ready,
7279 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
7280 * draw from the cache when the cache is enabled. To benefit from the cache, you must
7281 * request the drawing cache by calling this method and draw it on screen if the
7282 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007283 *
7284 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7285 * this method will create a bitmap of the same size as this view. Because this bitmap
7286 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7287 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7288 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7289 * size than the view. This implies that your application must be able to handle this
7290 * size.</p>
7291 *
7292 * @param autoScale Indicates whether the generated bitmap should be scaled based on
7293 * the current density of the screen when the application is in compatibility
7294 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 *
Romain Guyfbd8f692009-06-26 14:51:58 -07007296 * @return A bitmap representing this view or null if cache is disabled.
7297 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007298 * @see #setDrawingCacheEnabled(boolean)
7299 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07007300 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007301 * @see #destroyDrawingCache()
7302 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007303 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007304 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
7305 return null;
7306 }
7307 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007308 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007309 }
Romain Guy02890fd2010-08-06 17:58:44 -07007310 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007311 }
7312
7313 /**
7314 * <p>Frees the resources used by the drawing cache. If you call
7315 * {@link #buildDrawingCache()} manually without calling
7316 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7317 * should cleanup the cache with this method afterwards.</p>
7318 *
7319 * @see #setDrawingCacheEnabled(boolean)
7320 * @see #buildDrawingCache()
7321 * @see #getDrawingCache()
7322 */
7323 public void destroyDrawingCache() {
7324 if (mDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007325 mDrawingCache.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 mDrawingCache = null;
7327 }
Romain Guyfbd8f692009-06-26 14:51:58 -07007328 if (mUnscaledDrawingCache != null) {
Romain Guy02890fd2010-08-06 17:58:44 -07007329 mUnscaledDrawingCache.recycle();
Romain Guyfbd8f692009-06-26 14:51:58 -07007330 mUnscaledDrawingCache = null;
7331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007332 }
7333
7334 /**
7335 * Setting a solid background color for the drawing cache's bitmaps will improve
7336 * perfromance and memory usage. Note, though that this should only be used if this
7337 * view will always be drawn on top of a solid color.
7338 *
7339 * @param color The background color to use for the drawing cache's bitmap
7340 *
7341 * @see #setDrawingCacheEnabled(boolean)
7342 * @see #buildDrawingCache()
7343 * @see #getDrawingCache()
7344 */
7345 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08007346 if (color != mDrawingCacheBackgroundColor) {
7347 mDrawingCacheBackgroundColor = color;
7348 mPrivateFlags &= ~DRAWING_CACHE_VALID;
7349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007350 }
7351
7352 /**
7353 * @see #setDrawingCacheBackgroundColor(int)
7354 *
7355 * @return The background color to used for the drawing cache's bitmap
7356 */
7357 public int getDrawingCacheBackgroundColor() {
7358 return mDrawingCacheBackgroundColor;
7359 }
7360
7361 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07007362 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
7363 *
7364 * @see #buildDrawingCache(boolean)
7365 */
7366 public void buildDrawingCache() {
7367 buildDrawingCache(false);
7368 }
7369
7370 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
7372 *
7373 * <p>If you call {@link #buildDrawingCache()} manually without calling
7374 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
7375 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07007376 *
7377 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
7378 * this method will create a bitmap of the same size as this view. Because this bitmap
7379 * will be drawn scaled by the parent ViewGroup, the result on screen might show
7380 * scaling artifacts. To avoid such artifacts, you should call this method by setting
7381 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
7382 * size than the view. This implies that your application must be able to handle this
7383 * size.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007384 *
7385 * @see #getDrawingCache()
7386 * @see #destroyDrawingCache()
7387 */
Romain Guyfbd8f692009-06-26 14:51:58 -07007388 public void buildDrawingCache(boolean autoScale) {
7389 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
Romain Guy02890fd2010-08-06 17:58:44 -07007390 mDrawingCache == null : mUnscaledDrawingCache == null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007391
7392 if (ViewDebug.TRACE_HIERARCHY) {
7393 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
7394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395
Romain Guy8506ab42009-06-11 17:35:47 -07007396 int width = mRight - mLeft;
7397 int height = mBottom - mTop;
7398
7399 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07007400 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07007401
Romain Guye1123222009-06-29 14:24:56 -07007402 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007403 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
7404 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07007405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007406
7407 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07007408 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Romain Guya62e4702009-10-08 10:48:54 -07007409 final boolean translucentWindow = attachInfo != null && attachInfo.mTranslucentWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007410
7411 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07007412 // Projected bitmap size in bytes
7413 (width * height * (opaque && !translucentWindow ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007414 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
7415 destroyDrawingCache();
7416 return;
7417 }
7418
7419 boolean clear = true;
Romain Guy02890fd2010-08-06 17:58:44 -07007420 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421
7422 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007423 Bitmap.Config quality;
7424 if (!opaque) {
7425 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
7426 case DRAWING_CACHE_QUALITY_AUTO:
7427 quality = Bitmap.Config.ARGB_8888;
7428 break;
7429 case DRAWING_CACHE_QUALITY_LOW:
7430 quality = Bitmap.Config.ARGB_4444;
7431 break;
7432 case DRAWING_CACHE_QUALITY_HIGH:
7433 quality = Bitmap.Config.ARGB_8888;
7434 break;
7435 default:
7436 quality = Bitmap.Config.ARGB_8888;
7437 break;
7438 }
7439 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07007440 // Optimization for translucent windows
7441 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
7442 quality = translucentWindow ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007443 }
7444
7445 // Try to cleanup memory
7446 if (bitmap != null) bitmap.recycle();
7447
7448 try {
7449 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07007450 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07007451 if (autoScale) {
Romain Guy02890fd2010-08-06 17:58:44 -07007452 mDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007453 } else {
Romain Guy02890fd2010-08-06 17:58:44 -07007454 mUnscaledDrawingCache = bitmap;
Romain Guyfbd8f692009-06-26 14:51:58 -07007455 }
Romain Guy35b38ce2009-10-07 13:38:55 -07007456 if (opaque && translucentWindow) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007457 } catch (OutOfMemoryError e) {
7458 // If there is not enough memory to create the bitmap cache, just
7459 // ignore the issue as bitmap caches are not required to draw the
7460 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07007461 if (autoScale) {
7462 mDrawingCache = null;
7463 } else {
7464 mUnscaledDrawingCache = null;
7465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007466 return;
7467 }
7468
7469 clear = drawingCacheBackgroundColor != 0;
7470 }
7471
7472 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007473 if (attachInfo != null) {
7474 canvas = attachInfo.mCanvas;
7475 if (canvas == null) {
7476 canvas = new Canvas();
7477 }
7478 canvas.setBitmap(bitmap);
7479 // Temporarily clobber the cached Canvas in case one of our children
7480 // is also using a drawing cache. Without this, the children would
7481 // steal the canvas by attaching their own bitmap to it and bad, bad
7482 // thing would happen (invisible views, corrupted drawings, etc.)
7483 attachInfo.mCanvas = null;
7484 } else {
7485 // This case should hopefully never or seldom happen
7486 canvas = new Canvas(bitmap);
7487 }
7488
7489 if (clear) {
7490 bitmap.eraseColor(drawingCacheBackgroundColor);
7491 }
7492
7493 computeScroll();
7494 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07007495
Romain Guye1123222009-06-29 14:24:56 -07007496 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07007497 final float scale = attachInfo.mApplicationScale;
7498 canvas.scale(scale, scale);
7499 }
7500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007501 canvas.translate(-mScrollX, -mScrollY);
7502
Romain Guy5bcdff42009-05-14 21:27:18 -07007503 mPrivateFlags |= DRAWN;
Romain Guyecd80ee2009-12-03 17:13:02 -08007504 mPrivateFlags |= DRAWING_CACHE_VALID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007505
7506 // Fast path for layouts with no backgrounds
7507 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7508 if (ViewDebug.TRACE_HIERARCHY) {
7509 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7510 }
Romain Guy5bcdff42009-05-14 21:27:18 -07007511 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007512 dispatchDraw(canvas);
7513 } else {
7514 draw(canvas);
7515 }
7516
7517 canvas.restoreToCount(restoreCount);
7518
7519 if (attachInfo != null) {
7520 // Restore the cached Canvas for our siblings
7521 attachInfo.mCanvas = canvas;
7522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 }
7524 }
7525
7526 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007527 * Create a snapshot of the view into a bitmap. We should probably make
7528 * some form of this public, but should think about the API.
7529 */
Romain Guy223ff5c2010-03-02 17:07:47 -08007530 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007531 int width = mRight - mLeft;
7532 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007533
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007534 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07007535 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007536 width = (int) ((width * scale) + 0.5f);
7537 height = (int) ((height * scale) + 0.5f);
7538
Romain Guy8c11e312009-09-14 15:15:30 -07007539 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007540 if (bitmap == null) {
7541 throw new OutOfMemoryError();
7542 }
7543
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007544 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
7545
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007546 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007547 if (attachInfo != null) {
7548 canvas = attachInfo.mCanvas;
7549 if (canvas == null) {
7550 canvas = new Canvas();
7551 }
7552 canvas.setBitmap(bitmap);
7553 // Temporarily clobber the cached Canvas in case one of our children
7554 // is also using a drawing cache. Without this, the children would
7555 // steal the canvas by attaching their own bitmap to it and bad, bad
7556 // things would happen (invisible views, corrupted drawings, etc.)
7557 attachInfo.mCanvas = null;
7558 } else {
7559 // This case should hopefully never or seldom happen
7560 canvas = new Canvas(bitmap);
7561 }
7562
Romain Guy5bcdff42009-05-14 21:27:18 -07007563 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007564 bitmap.eraseColor(backgroundColor);
7565 }
7566
7567 computeScroll();
7568 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07007569 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007570 canvas.translate(-mScrollX, -mScrollY);
7571
Romain Guy5bcdff42009-05-14 21:27:18 -07007572 // Temporarily remove the dirty mask
7573 int flags = mPrivateFlags;
7574 mPrivateFlags &= ~DIRTY_MASK;
7575
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007576 // Fast path for layouts with no backgrounds
7577 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
7578 dispatchDraw(canvas);
7579 } else {
7580 draw(canvas);
7581 }
7582
Romain Guy5bcdff42009-05-14 21:27:18 -07007583 mPrivateFlags = flags;
7584
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007585 canvas.restoreToCount(restoreCount);
7586
7587 if (attachInfo != null) {
7588 // Restore the cached Canvas for our siblings
7589 attachInfo.mCanvas = canvas;
7590 }
Romain Guy8506ab42009-06-11 17:35:47 -07007591
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007592 return bitmap;
7593 }
7594
7595 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007596 * Indicates whether this View is currently in edit mode. A View is usually
7597 * in edit mode when displayed within a developer tool. For instance, if
7598 * this View is being drawn by a visual user interface builder, this method
7599 * should return true.
7600 *
7601 * Subclasses should check the return value of this method to provide
7602 * different behaviors if their normal behavior might interfere with the
7603 * host environment. For instance: the class spawns a thread in its
7604 * constructor, the drawing code relies on device-specific features, etc.
7605 *
7606 * This method is usually checked in the drawing code of custom widgets.
7607 *
7608 * @return True if this View is in edit mode, false otherwise.
7609 */
7610 public boolean isInEditMode() {
7611 return false;
7612 }
7613
7614 /**
7615 * If the View draws content inside its padding and enables fading edges,
7616 * it needs to support padding offsets. Padding offsets are added to the
7617 * fading edges to extend the length of the fade so that it covers pixels
7618 * drawn inside the padding.
7619 *
7620 * Subclasses of this class should override this method if they need
7621 * to draw content inside the padding.
7622 *
7623 * @return True if padding offset must be applied, false otherwise.
7624 *
7625 * @see #getLeftPaddingOffset()
7626 * @see #getRightPaddingOffset()
7627 * @see #getTopPaddingOffset()
7628 * @see #getBottomPaddingOffset()
7629 *
7630 * @since CURRENT
7631 */
7632 protected boolean isPaddingOffsetRequired() {
7633 return false;
7634 }
7635
7636 /**
7637 * Amount by which to extend the left fading region. Called only when
7638 * {@link #isPaddingOffsetRequired()} returns true.
7639 *
7640 * @return The left padding offset in pixels.
7641 *
7642 * @see #isPaddingOffsetRequired()
7643 *
7644 * @since CURRENT
7645 */
7646 protected int getLeftPaddingOffset() {
7647 return 0;
7648 }
7649
7650 /**
7651 * Amount by which to extend the right fading region. Called only when
7652 * {@link #isPaddingOffsetRequired()} returns true.
7653 *
7654 * @return The right padding offset in pixels.
7655 *
7656 * @see #isPaddingOffsetRequired()
7657 *
7658 * @since CURRENT
7659 */
7660 protected int getRightPaddingOffset() {
7661 return 0;
7662 }
7663
7664 /**
7665 * Amount by which to extend the top fading region. Called only when
7666 * {@link #isPaddingOffsetRequired()} returns true.
7667 *
7668 * @return The top padding offset in pixels.
7669 *
7670 * @see #isPaddingOffsetRequired()
7671 *
7672 * @since CURRENT
7673 */
7674 protected int getTopPaddingOffset() {
7675 return 0;
7676 }
7677
7678 /**
7679 * Amount by which to extend the bottom fading region. Called only when
7680 * {@link #isPaddingOffsetRequired()} returns true.
7681 *
7682 * @return The bottom padding offset in pixels.
7683 *
7684 * @see #isPaddingOffsetRequired()
7685 *
7686 * @since CURRENT
7687 */
7688 protected int getBottomPaddingOffset() {
7689 return 0;
7690 }
7691
7692 /**
7693 * Manually render this view (and all of its children) to the given Canvas.
7694 * The view must have already done a full layout before this function is
7695 * called. When implementing a view, do not override this method; instead,
7696 * you should implement {@link #onDraw}.
7697 *
7698 * @param canvas The Canvas to which the View is rendered.
7699 */
7700 public void draw(Canvas canvas) {
7701 if (ViewDebug.TRACE_HIERARCHY) {
7702 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
7703 }
7704
Romain Guy5bcdff42009-05-14 21:27:18 -07007705 final int privateFlags = mPrivateFlags;
7706 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
7707 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
7708 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07007709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710 /*
7711 * Draw traversal performs several drawing steps which must be executed
7712 * in the appropriate order:
7713 *
7714 * 1. Draw the background
7715 * 2. If necessary, save the canvas' layers to prepare for fading
7716 * 3. Draw view's content
7717 * 4. Draw children
7718 * 5. If necessary, draw the fading edges and restore layers
7719 * 6. Draw decorations (scrollbars for instance)
7720 */
7721
7722 // Step 1, draw the background, if needed
7723 int saveCount;
7724
Romain Guy24443ea2009-05-11 11:56:30 -07007725 if (!dirtyOpaque) {
7726 final Drawable background = mBGDrawable;
7727 if (background != null) {
7728 final int scrollX = mScrollX;
7729 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730
Romain Guy24443ea2009-05-11 11:56:30 -07007731 if (mBackgroundSizeChanged) {
7732 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
7733 mBackgroundSizeChanged = false;
7734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735
Romain Guy24443ea2009-05-11 11:56:30 -07007736 if ((scrollX | scrollY) == 0) {
7737 background.draw(canvas);
7738 } else {
7739 canvas.translate(scrollX, scrollY);
7740 background.draw(canvas);
7741 canvas.translate(-scrollX, -scrollY);
7742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007743 }
7744 }
7745
7746 // skip step 2 & 5 if possible (common case)
7747 final int viewFlags = mViewFlags;
7748 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
7749 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
7750 if (!verticalEdges && !horizontalEdges) {
7751 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007752 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753
7754 // Step 4, draw the children
7755 dispatchDraw(canvas);
7756
7757 // Step 6, draw decorations (scrollbars)
7758 onDrawScrollBars(canvas);
7759
7760 // we're done...
7761 return;
7762 }
7763
7764 /*
7765 * Here we do the full fledged routine...
7766 * (this is an uncommon case where speed matters less,
7767 * this is why we repeat some of the tests that have been
7768 * done above)
7769 */
7770
7771 boolean drawTop = false;
7772 boolean drawBottom = false;
7773 boolean drawLeft = false;
7774 boolean drawRight = false;
7775
7776 float topFadeStrength = 0.0f;
7777 float bottomFadeStrength = 0.0f;
7778 float leftFadeStrength = 0.0f;
7779 float rightFadeStrength = 0.0f;
7780
7781 // Step 2, save the canvas' layers
7782 int paddingLeft = mPaddingLeft;
7783 int paddingTop = mPaddingTop;
7784
7785 final boolean offsetRequired = isPaddingOffsetRequired();
7786 if (offsetRequired) {
7787 paddingLeft += getLeftPaddingOffset();
7788 paddingTop += getTopPaddingOffset();
7789 }
7790
7791 int left = mScrollX + paddingLeft;
7792 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
7793 int top = mScrollY + paddingTop;
7794 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
7795
7796 if (offsetRequired) {
7797 right += getRightPaddingOffset();
7798 bottom += getBottomPaddingOffset();
7799 }
7800
7801 final ScrollabilityCache scrollabilityCache = mScrollCache;
7802 int length = scrollabilityCache.fadingEdgeLength;
7803
7804 // clip the fade length if top and bottom fades overlap
7805 // overlapping fades produce odd-looking artifacts
7806 if (verticalEdges && (top + length > bottom - length)) {
7807 length = (bottom - top) / 2;
7808 }
7809
7810 // also clip horizontal fades if necessary
7811 if (horizontalEdges && (left + length > right - length)) {
7812 length = (right - left) / 2;
7813 }
7814
7815 if (verticalEdges) {
7816 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007817 drawTop = topFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007819 drawBottom = bottomFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007820 }
7821
7822 if (horizontalEdges) {
7823 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007824 drawLeft = leftFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007825 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
Romain Guydac5f9f2010-07-08 11:40:54 -07007826 drawRight = rightFadeStrength > 0.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007827 }
7828
7829 saveCount = canvas.getSaveCount();
7830
7831 int solidColor = getSolidColor();
Romain Guy14cd0652010-09-07 12:01:38 -07007832 // TODO: Temporarily disable fading edges with hardware acceleration
7833 if (solidColor == 0 && !canvas.isHardwareAccelerated()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007834 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
7835
7836 if (drawTop) {
7837 canvas.saveLayer(left, top, right, top + length, null, flags);
7838 }
7839
7840 if (drawBottom) {
7841 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
7842 }
7843
7844 if (drawLeft) {
7845 canvas.saveLayer(left, top, left + length, bottom, null, flags);
7846 }
7847
7848 if (drawRight) {
7849 canvas.saveLayer(right - length, top, right, bottom, null, flags);
7850 }
7851 } else {
7852 scrollabilityCache.setFadeColor(solidColor);
7853 }
7854
7855 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07007856 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857
7858 // Step 4, draw the children
7859 dispatchDraw(canvas);
7860
7861 // Step 5, draw the fade effect and restore layers
7862 final Paint p = scrollabilityCache.paint;
7863 final Matrix matrix = scrollabilityCache.matrix;
7864 final Shader fade = scrollabilityCache.shader;
7865 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
7866
7867 if (drawTop) {
7868 matrix.setScale(1, fadeHeight * topFadeStrength);
7869 matrix.postTranslate(left, top);
7870 fade.setLocalMatrix(matrix);
7871 canvas.drawRect(left, top, right, top + length, p);
7872 }
7873
7874 if (drawBottom) {
7875 matrix.setScale(1, fadeHeight * bottomFadeStrength);
7876 matrix.postRotate(180);
7877 matrix.postTranslate(left, bottom);
7878 fade.setLocalMatrix(matrix);
7879 canvas.drawRect(left, bottom - length, right, bottom, p);
7880 }
7881
7882 if (drawLeft) {
7883 matrix.setScale(1, fadeHeight * leftFadeStrength);
7884 matrix.postRotate(-90);
7885 matrix.postTranslate(left, top);
7886 fade.setLocalMatrix(matrix);
7887 canvas.drawRect(left, top, left + length, bottom, p);
7888 }
7889
7890 if (drawRight) {
7891 matrix.setScale(1, fadeHeight * rightFadeStrength);
7892 matrix.postRotate(90);
7893 matrix.postTranslate(right, top);
7894 fade.setLocalMatrix(matrix);
7895 canvas.drawRect(right - length, top, right, bottom, p);
7896 }
7897
7898 canvas.restoreToCount(saveCount);
7899
7900 // Step 6, draw decorations (scrollbars)
7901 onDrawScrollBars(canvas);
7902 }
7903
7904 /**
7905 * Override this if your view is known to always be drawn on top of a solid color background,
7906 * and needs to draw fading edges. Returning a non-zero color enables the view system to
7907 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
7908 * should be set to 0xFF.
7909 *
7910 * @see #setVerticalFadingEdgeEnabled
7911 * @see #setHorizontalFadingEdgeEnabled
7912 *
7913 * @return The known solid color background for this view, or 0 if the color may vary
7914 */
7915 public int getSolidColor() {
7916 return 0;
7917 }
7918
7919 /**
7920 * Build a human readable string representation of the specified view flags.
7921 *
7922 * @param flags the view flags to convert to a string
7923 * @return a String representing the supplied flags
7924 */
7925 private static String printFlags(int flags) {
7926 String output = "";
7927 int numFlags = 0;
7928 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
7929 output += "TAKES_FOCUS";
7930 numFlags++;
7931 }
7932
7933 switch (flags & VISIBILITY_MASK) {
7934 case INVISIBLE:
7935 if (numFlags > 0) {
7936 output += " ";
7937 }
7938 output += "INVISIBLE";
7939 // USELESS HERE numFlags++;
7940 break;
7941 case GONE:
7942 if (numFlags > 0) {
7943 output += " ";
7944 }
7945 output += "GONE";
7946 // USELESS HERE numFlags++;
7947 break;
7948 default:
7949 break;
7950 }
7951 return output;
7952 }
7953
7954 /**
7955 * Build a human readable string representation of the specified private
7956 * view flags.
7957 *
7958 * @param privateFlags the private view flags to convert to a string
7959 * @return a String representing the supplied flags
7960 */
7961 private static String printPrivateFlags(int privateFlags) {
7962 String output = "";
7963 int numFlags = 0;
7964
7965 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
7966 output += "WANTS_FOCUS";
7967 numFlags++;
7968 }
7969
7970 if ((privateFlags & FOCUSED) == FOCUSED) {
7971 if (numFlags > 0) {
7972 output += " ";
7973 }
7974 output += "FOCUSED";
7975 numFlags++;
7976 }
7977
7978 if ((privateFlags & SELECTED) == SELECTED) {
7979 if (numFlags > 0) {
7980 output += " ";
7981 }
7982 output += "SELECTED";
7983 numFlags++;
7984 }
7985
7986 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
7987 if (numFlags > 0) {
7988 output += " ";
7989 }
7990 output += "IS_ROOT_NAMESPACE";
7991 numFlags++;
7992 }
7993
7994 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
7995 if (numFlags > 0) {
7996 output += " ";
7997 }
7998 output += "HAS_BOUNDS";
7999 numFlags++;
8000 }
8001
8002 if ((privateFlags & DRAWN) == DRAWN) {
8003 if (numFlags > 0) {
8004 output += " ";
8005 }
8006 output += "DRAWN";
8007 // USELESS HERE numFlags++;
8008 }
8009 return output;
8010 }
8011
8012 /**
8013 * <p>Indicates whether or not this view's layout will be requested during
8014 * the next hierarchy layout pass.</p>
8015 *
8016 * @return true if the layout will be forced during next layout pass
8017 */
8018 public boolean isLayoutRequested() {
8019 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8020 }
8021
8022 /**
8023 * Assign a size and position to a view and all of its
8024 * descendants
8025 *
8026 * <p>This is the second phase of the layout mechanism.
8027 * (The first is measuring). In this phase, each parent calls
8028 * layout on all of its children to position them.
8029 * This is typically done using the child measurements
8030 * that were stored in the measure pass().
8031 *
8032 * Derived classes with children should override
8033 * onLayout. In that method, they should
Chet Haase21cd1382010-09-01 17:42:29 -07008034 * call layout on each of their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 *
8036 * @param l Left position, relative to parent
8037 * @param t Top position, relative to parent
8038 * @param r Right position, relative to parent
8039 * @param b Bottom position, relative to parent
8040 */
Romain Guy5429e1d2010-09-07 12:38:00 -07008041 @SuppressWarnings({"unchecked"})
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008042 public final void layout(int l, int t, int r, int b) {
Chet Haase21cd1382010-09-01 17:42:29 -07008043 int oldL = mLeft;
8044 int oldT = mTop;
8045 int oldB = mBottom;
8046 int oldR = mRight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008047 boolean changed = setFrame(l, t, r, b);
8048 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8049 if (ViewDebug.TRACE_HIERARCHY) {
8050 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8051 }
8052
8053 onLayout(changed, l, t, r, b);
8054 mPrivateFlags &= ~LAYOUT_REQUIRED;
Chet Haase21cd1382010-09-01 17:42:29 -07008055
8056 if (mOnLayoutChangeListeners != null) {
8057 ArrayList<OnLayoutChangeListener> listenersCopy =
8058 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8059 int numListeners = listenersCopy.size();
8060 for (int i = 0; i < numListeners; ++i) {
8061 listenersCopy.get(i).onLayoutChange(this, l, r, t, b, oldL, oldT, oldR, oldB);
8062 }
8063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 }
8065 mPrivateFlags &= ~FORCE_LAYOUT;
8066 }
8067
8068 /**
8069 * Called from layout when this view should
8070 * assign a size and position to each of its children.
8071 *
8072 * Derived classes with children should override
8073 * this method and call layout on each of
Chet Haase21cd1382010-09-01 17:42:29 -07008074 * their children.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008075 * @param changed This is a new size or position for this view
8076 * @param left Left position, relative to parent
8077 * @param top Top position, relative to parent
8078 * @param right Right position, relative to parent
8079 * @param bottom Bottom position, relative to parent
8080 */
8081 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
8082 }
8083
8084 /**
8085 * Assign a size and position to this view.
8086 *
8087 * This is called from layout.
8088 *
8089 * @param left Left position, relative to parent
8090 * @param top Top position, relative to parent
8091 * @param right Right position, relative to parent
8092 * @param bottom Bottom position, relative to parent
8093 * @return true if the new size and position are different than the
8094 * previous ones
8095 * {@hide}
8096 */
8097 protected boolean setFrame(int left, int top, int right, int bottom) {
8098 boolean changed = false;
8099
8100 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07008101 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008102 + right + "," + bottom + ")");
8103 }
8104
8105 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
8106 changed = true;
8107
8108 // Remember our drawn bit
8109 int drawn = mPrivateFlags & DRAWN;
8110
8111 // Invalidate our old position
8112 invalidate();
8113
8114
8115 int oldWidth = mRight - mLeft;
8116 int oldHeight = mBottom - mTop;
8117
8118 mLeft = left;
8119 mTop = top;
8120 mRight = right;
8121 mBottom = bottom;
8122
8123 mPrivateFlags |= HAS_BOUNDS;
8124
8125 int newWidth = right - left;
8126 int newHeight = bottom - top;
8127
8128 if (newWidth != oldWidth || newHeight != oldHeight) {
8129 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
8130 }
8131
8132 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
8133 // If we are visible, force the DRAWN bit to on so that
8134 // this invalidate will go through (at least to our parent).
8135 // This is because someone may have invalidated this view
8136 // before this call to setFrame came in, therby clearing
8137 // the DRAWN bit.
8138 mPrivateFlags |= DRAWN;
8139 invalidate();
8140 }
8141
8142 // Reset drawn bit to original value (invalidate turns it off)
8143 mPrivateFlags |= drawn;
8144
8145 mBackgroundSizeChanged = true;
8146 }
8147 return changed;
8148 }
8149
8150 /**
8151 * Finalize inflating a view from XML. This is called as the last phase
8152 * of inflation, after all child views have been added.
8153 *
8154 * <p>Even if the subclass overrides onFinishInflate, they should always be
8155 * sure to call the super method, so that we get called.
8156 */
8157 protected void onFinishInflate() {
8158 }
8159
8160 /**
8161 * Returns the resources associated with this view.
8162 *
8163 * @return Resources object.
8164 */
8165 public Resources getResources() {
8166 return mResources;
8167 }
8168
8169 /**
8170 * Invalidates the specified Drawable.
8171 *
8172 * @param drawable the drawable to invalidate
8173 */
8174 public void invalidateDrawable(Drawable drawable) {
8175 if (verifyDrawable(drawable)) {
8176 final Rect dirty = drawable.getBounds();
8177 final int scrollX = mScrollX;
8178 final int scrollY = mScrollY;
8179
8180 invalidate(dirty.left + scrollX, dirty.top + scrollY,
8181 dirty.right + scrollX, dirty.bottom + scrollY);
8182 }
8183 }
8184
8185 /**
8186 * Schedules an action on a drawable to occur at a specified time.
8187 *
8188 * @param who the recipient of the action
8189 * @param what the action to run on the drawable
8190 * @param when the time at which the action must occur. Uses the
8191 * {@link SystemClock#uptimeMillis} timebase.
8192 */
8193 public void scheduleDrawable(Drawable who, Runnable what, long when) {
8194 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8195 mAttachInfo.mHandler.postAtTime(what, who, when);
8196 }
8197 }
8198
8199 /**
8200 * Cancels a scheduled action on a drawable.
8201 *
8202 * @param who the recipient of the action
8203 * @param what the action to cancel
8204 */
8205 public void unscheduleDrawable(Drawable who, Runnable what) {
8206 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
8207 mAttachInfo.mHandler.removeCallbacks(what, who);
8208 }
8209 }
8210
8211 /**
8212 * Unschedule any events associated with the given Drawable. This can be
8213 * used when selecting a new Drawable into a view, so that the previous
8214 * one is completely unscheduled.
8215 *
8216 * @param who The Drawable to unschedule.
8217 *
8218 * @see #drawableStateChanged
8219 */
8220 public void unscheduleDrawable(Drawable who) {
8221 if (mAttachInfo != null) {
8222 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
8223 }
8224 }
8225
8226 /**
8227 * If your view subclass is displaying its own Drawable objects, it should
8228 * override this function and return true for any Drawable it is
8229 * displaying. This allows animations for those drawables to be
8230 * scheduled.
8231 *
8232 * <p>Be sure to call through to the super class when overriding this
8233 * function.
8234 *
8235 * @param who The Drawable to verify. Return true if it is one you are
8236 * displaying, else return the result of calling through to the
8237 * super class.
8238 *
8239 * @return boolean If true than the Drawable is being displayed in the
8240 * view; else false and it is not allowed to animate.
8241 *
8242 * @see #unscheduleDrawable
8243 * @see #drawableStateChanged
8244 */
8245 protected boolean verifyDrawable(Drawable who) {
8246 return who == mBGDrawable;
8247 }
8248
8249 /**
8250 * This function is called whenever the state of the view changes in such
8251 * a way that it impacts the state of drawables being shown.
8252 *
8253 * <p>Be sure to call through to the superclass when overriding this
8254 * function.
8255 *
8256 * @see Drawable#setState
8257 */
8258 protected void drawableStateChanged() {
8259 Drawable d = mBGDrawable;
8260 if (d != null && d.isStateful()) {
8261 d.setState(getDrawableState());
8262 }
8263 }
8264
8265 /**
8266 * Call this to force a view to update its drawable state. This will cause
8267 * drawableStateChanged to be called on this view. Views that are interested
8268 * in the new state should call getDrawableState.
8269 *
8270 * @see #drawableStateChanged
8271 * @see #getDrawableState
8272 */
8273 public void refreshDrawableState() {
8274 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
8275 drawableStateChanged();
8276
8277 ViewParent parent = mParent;
8278 if (parent != null) {
8279 parent.childDrawableStateChanged(this);
8280 }
8281 }
8282
8283 /**
8284 * Return an array of resource IDs of the drawable states representing the
8285 * current state of the view.
8286 *
8287 * @return The current drawable state
8288 *
8289 * @see Drawable#setState
8290 * @see #drawableStateChanged
8291 * @see #onCreateDrawableState
8292 */
8293 public final int[] getDrawableState() {
8294 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
8295 return mDrawableState;
8296 } else {
8297 mDrawableState = onCreateDrawableState(0);
8298 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
8299 return mDrawableState;
8300 }
8301 }
8302
8303 /**
8304 * Generate the new {@link android.graphics.drawable.Drawable} state for
8305 * this view. This is called by the view
8306 * system when the cached Drawable state is determined to be invalid. To
8307 * retrieve the current state, you should use {@link #getDrawableState}.
8308 *
8309 * @param extraSpace if non-zero, this is the number of extra entries you
8310 * would like in the returned array in which you can place your own
8311 * states.
8312 *
8313 * @return Returns an array holding the current {@link Drawable} state of
8314 * the view.
8315 *
8316 * @see #mergeDrawableStates
8317 */
8318 protected int[] onCreateDrawableState(int extraSpace) {
8319 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
8320 mParent instanceof View) {
8321 return ((View) mParent).onCreateDrawableState(extraSpace);
8322 }
8323
8324 int[] drawableState;
8325
8326 int privateFlags = mPrivateFlags;
8327
8328 int viewStateIndex = (((privateFlags & PRESSED) != 0) ? 1 : 0);
8329
8330 viewStateIndex = (viewStateIndex << 1)
8331 + (((mViewFlags & ENABLED_MASK) == ENABLED) ? 1 : 0);
8332
8333 viewStateIndex = (viewStateIndex << 1) + (isFocused() ? 1 : 0);
8334
8335 viewStateIndex = (viewStateIndex << 1)
8336 + (((privateFlags & SELECTED) != 0) ? 1 : 0);
8337
8338 final boolean hasWindowFocus = hasWindowFocus();
8339 viewStateIndex = (viewStateIndex << 1) + (hasWindowFocus ? 1 : 0);
8340
8341 drawableState = VIEW_STATE_SETS[viewStateIndex];
8342
8343 //noinspection ConstantIfStatement
8344 if (false) {
8345 Log.i("View", "drawableStateIndex=" + viewStateIndex);
8346 Log.i("View", toString()
8347 + " pressed=" + ((privateFlags & PRESSED) != 0)
8348 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
8349 + " fo=" + hasFocus()
8350 + " sl=" + ((privateFlags & SELECTED) != 0)
8351 + " wf=" + hasWindowFocus
8352 + ": " + Arrays.toString(drawableState));
8353 }
8354
8355 if (extraSpace == 0) {
8356 return drawableState;
8357 }
8358
8359 final int[] fullState;
8360 if (drawableState != null) {
8361 fullState = new int[drawableState.length + extraSpace];
8362 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
8363 } else {
8364 fullState = new int[extraSpace];
8365 }
8366
8367 return fullState;
8368 }
8369
8370 /**
8371 * Merge your own state values in <var>additionalState</var> into the base
8372 * state values <var>baseState</var> that were returned by
8373 * {@link #onCreateDrawableState}.
8374 *
8375 * @param baseState The base state values returned by
8376 * {@link #onCreateDrawableState}, which will be modified to also hold your
8377 * own additional state values.
8378 *
8379 * @param additionalState The additional state values you would like
8380 * added to <var>baseState</var>; this array is not modified.
8381 *
8382 * @return As a convenience, the <var>baseState</var> array you originally
8383 * passed into the function is returned.
8384 *
8385 * @see #onCreateDrawableState
8386 */
8387 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
8388 final int N = baseState.length;
8389 int i = N - 1;
8390 while (i >= 0 && baseState[i] == 0) {
8391 i--;
8392 }
8393 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
8394 return baseState;
8395 }
8396
8397 /**
8398 * Sets the background color for this view.
8399 * @param color the color of the background
8400 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008401 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008402 public void setBackgroundColor(int color) {
8403 setBackgroundDrawable(new ColorDrawable(color));
8404 }
8405
8406 /**
8407 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07008408 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 * @param resid The identifier of the resource.
8410 * @attr ref android.R.styleable#View_background
8411 */
Bjorn Bringert8354fa62010-02-24 23:54:29 +00008412 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008413 public void setBackgroundResource(int resid) {
8414 if (resid != 0 && resid == mBackgroundResource) {
8415 return;
8416 }
8417
8418 Drawable d= null;
8419 if (resid != 0) {
8420 d = mResources.getDrawable(resid);
8421 }
8422 setBackgroundDrawable(d);
8423
8424 mBackgroundResource = resid;
8425 }
8426
8427 /**
8428 * Set the background to a given Drawable, or remove the background. If the
8429 * background has padding, this View's padding is set to the background's
8430 * padding. However, when a background is removed, this View's padding isn't
8431 * touched. If setting the padding is desired, please use
8432 * {@link #setPadding(int, int, int, int)}.
8433 *
8434 * @param d The Drawable to use as the background, or null to remove the
8435 * background
8436 */
8437 public void setBackgroundDrawable(Drawable d) {
8438 boolean requestLayout = false;
8439
8440 mBackgroundResource = 0;
8441
8442 /*
8443 * Regardless of whether we're setting a new background or not, we want
8444 * to clear the previous drawable.
8445 */
8446 if (mBGDrawable != null) {
8447 mBGDrawable.setCallback(null);
8448 unscheduleDrawable(mBGDrawable);
8449 }
8450
8451 if (d != null) {
8452 Rect padding = sThreadLocal.get();
8453 if (padding == null) {
8454 padding = new Rect();
8455 sThreadLocal.set(padding);
8456 }
8457 if (d.getPadding(padding)) {
8458 setPadding(padding.left, padding.top, padding.right, padding.bottom);
8459 }
8460
8461 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
8462 // if it has a different minimum size, we should layout again
8463 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
8464 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
8465 requestLayout = true;
8466 }
8467
8468 d.setCallback(this);
8469 if (d.isStateful()) {
8470 d.setState(getDrawableState());
8471 }
8472 d.setVisible(getVisibility() == VISIBLE, false);
8473 mBGDrawable = d;
8474
8475 if ((mPrivateFlags & SKIP_DRAW) != 0) {
8476 mPrivateFlags &= ~SKIP_DRAW;
8477 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8478 requestLayout = true;
8479 }
8480 } else {
8481 /* Remove the background */
8482 mBGDrawable = null;
8483
8484 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
8485 /*
8486 * This view ONLY drew the background before and we're removing
8487 * the background, so now it won't draw anything
8488 * (hence we SKIP_DRAW)
8489 */
8490 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
8491 mPrivateFlags |= SKIP_DRAW;
8492 }
8493
8494 /*
8495 * When the background is set, we try to apply its padding to this
8496 * View. When the background is removed, we don't touch this View's
8497 * padding. This is noted in the Javadocs. Hence, we don't need to
8498 * requestLayout(), the invalidate() below is sufficient.
8499 */
8500
8501 // The old background's minimum size could have affected this
8502 // View's layout, so let's requestLayout
8503 requestLayout = true;
8504 }
8505
Romain Guy8f1344f52009-05-15 16:03:59 -07008506 computeOpaqueFlags();
8507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008508 if (requestLayout) {
8509 requestLayout();
8510 }
8511
8512 mBackgroundSizeChanged = true;
8513 invalidate();
8514 }
8515
8516 /**
8517 * Gets the background drawable
8518 * @return The drawable used as the background for this view, if any.
8519 */
8520 public Drawable getBackground() {
8521 return mBGDrawable;
8522 }
8523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008524 /**
8525 * Sets the padding. The view may add on the space required to display
8526 * the scrollbars, depending on the style and visibility of the scrollbars.
8527 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
8528 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
8529 * from the values set in this call.
8530 *
8531 * @attr ref android.R.styleable#View_padding
8532 * @attr ref android.R.styleable#View_paddingBottom
8533 * @attr ref android.R.styleable#View_paddingLeft
8534 * @attr ref android.R.styleable#View_paddingRight
8535 * @attr ref android.R.styleable#View_paddingTop
8536 * @param left the left padding in pixels
8537 * @param top the top padding in pixels
8538 * @param right the right padding in pixels
8539 * @param bottom the bottom padding in pixels
8540 */
8541 public void setPadding(int left, int top, int right, int bottom) {
8542 boolean changed = false;
8543
8544 mUserPaddingRight = right;
8545 mUserPaddingBottom = bottom;
8546
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008547 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07008548
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008549 // Common case is there are no scroll bars.
8550 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
8551 // TODO: Deal with RTL languages to adjust left padding instead of right.
8552 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
8553 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8554 ? 0 : getVerticalScrollbarWidth();
8555 }
8556 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
8557 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
8558 ? 0 : getHorizontalScrollbarHeight();
8559 }
8560 }
Romain Guy8506ab42009-06-11 17:35:47 -07008561
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008562 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 changed = true;
8564 mPaddingLeft = left;
8565 }
8566 if (mPaddingTop != top) {
8567 changed = true;
8568 mPaddingTop = top;
8569 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008570 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008571 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008572 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008573 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008574 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008575 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07008576 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 }
8578
8579 if (changed) {
8580 requestLayout();
8581 }
8582 }
8583
8584 /**
8585 * Returns the top padding of this view.
8586 *
8587 * @return the top padding in pixels
8588 */
8589 public int getPaddingTop() {
8590 return mPaddingTop;
8591 }
8592
8593 /**
8594 * Returns the bottom padding of this view. If there are inset and enabled
8595 * scrollbars, this value may include the space required to display the
8596 * scrollbars as well.
8597 *
8598 * @return the bottom padding in pixels
8599 */
8600 public int getPaddingBottom() {
8601 return mPaddingBottom;
8602 }
8603
8604 /**
8605 * Returns the left padding of this view. If there are inset and enabled
8606 * scrollbars, this value may include the space required to display the
8607 * scrollbars as well.
8608 *
8609 * @return the left padding in pixels
8610 */
8611 public int getPaddingLeft() {
8612 return mPaddingLeft;
8613 }
8614
8615 /**
8616 * Returns the right padding of this view. If there are inset and enabled
8617 * scrollbars, this value may include the space required to display the
8618 * scrollbars as well.
8619 *
8620 * @return the right padding in pixels
8621 */
8622 public int getPaddingRight() {
8623 return mPaddingRight;
8624 }
8625
8626 /**
8627 * Changes the selection state of this view. A view can be selected or not.
8628 * Note that selection is not the same as focus. Views are typically
8629 * selected in the context of an AdapterView like ListView or GridView;
8630 * the selected view is the view that is highlighted.
8631 *
8632 * @param selected true if the view must be selected, false otherwise
8633 */
8634 public void setSelected(boolean selected) {
8635 if (((mPrivateFlags & SELECTED) != 0) != selected) {
8636 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07008637 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008638 invalidate();
8639 refreshDrawableState();
8640 dispatchSetSelected(selected);
8641 }
8642 }
8643
8644 /**
8645 * Dispatch setSelected to all of this View's children.
8646 *
8647 * @see #setSelected(boolean)
8648 *
8649 * @param selected The new selected state
8650 */
8651 protected void dispatchSetSelected(boolean selected) {
8652 }
8653
8654 /**
8655 * Indicates the selection state of this view.
8656 *
8657 * @return true if the view is selected, false otherwise
8658 */
8659 @ViewDebug.ExportedProperty
8660 public boolean isSelected() {
8661 return (mPrivateFlags & SELECTED) != 0;
8662 }
8663
8664 /**
8665 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
8666 * observer can be used to get notifications when global events, like
8667 * layout, happen.
8668 *
8669 * The returned ViewTreeObserver observer is not guaranteed to remain
8670 * valid for the lifetime of this View. If the caller of this method keeps
8671 * a long-lived reference to ViewTreeObserver, it should always check for
8672 * the return value of {@link ViewTreeObserver#isAlive()}.
8673 *
8674 * @return The ViewTreeObserver for this view's hierarchy.
8675 */
8676 public ViewTreeObserver getViewTreeObserver() {
8677 if (mAttachInfo != null) {
8678 return mAttachInfo.mTreeObserver;
8679 }
8680 if (mFloatingTreeObserver == null) {
8681 mFloatingTreeObserver = new ViewTreeObserver();
8682 }
8683 return mFloatingTreeObserver;
8684 }
8685
8686 /**
8687 * <p>Finds the topmost view in the current view hierarchy.</p>
8688 *
8689 * @return the topmost view containing this view
8690 */
8691 public View getRootView() {
8692 if (mAttachInfo != null) {
8693 final View v = mAttachInfo.mRootView;
8694 if (v != null) {
8695 return v;
8696 }
8697 }
Romain Guy8506ab42009-06-11 17:35:47 -07008698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008699 View parent = this;
8700
8701 while (parent.mParent != null && parent.mParent instanceof View) {
8702 parent = (View) parent.mParent;
8703 }
8704
8705 return parent;
8706 }
8707
8708 /**
8709 * <p>Computes the coordinates of this view on the screen. The argument
8710 * must be an array of two integers. After the method returns, the array
8711 * contains the x and y location in that order.</p>
8712 *
8713 * @param location an array of two integers in which to hold the coordinates
8714 */
8715 public void getLocationOnScreen(int[] location) {
8716 getLocationInWindow(location);
8717
8718 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07008719 if (info != null) {
8720 location[0] += info.mWindowLeft;
8721 location[1] += info.mWindowTop;
8722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723 }
8724
8725 /**
8726 * <p>Computes the coordinates of this view in its window. The argument
8727 * must be an array of two integers. After the method returns, the array
8728 * contains the x and y location in that order.</p>
8729 *
8730 * @param location an array of two integers in which to hold the coordinates
8731 */
8732 public void getLocationInWindow(int[] location) {
8733 if (location == null || location.length < 2) {
8734 throw new IllegalArgumentException("location must be an array of "
8735 + "two integers");
8736 }
8737
8738 location[0] = mLeft;
8739 location[1] = mTop;
8740
8741 ViewParent viewParent = mParent;
8742 while (viewParent instanceof View) {
8743 final View view = (View)viewParent;
8744 location[0] += view.mLeft - view.mScrollX;
8745 location[1] += view.mTop - view.mScrollY;
8746 viewParent = view.mParent;
8747 }
Romain Guy8506ab42009-06-11 17:35:47 -07008748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008749 if (viewParent instanceof ViewRoot) {
8750 // *cough*
8751 final ViewRoot vr = (ViewRoot)viewParent;
8752 location[1] -= vr.mCurScrollY;
8753 }
8754 }
8755
8756 /**
8757 * {@hide}
8758 * @param id the id of the view to be found
8759 * @return the view of the specified id, null if cannot be found
8760 */
8761 protected View findViewTraversal(int id) {
8762 if (id == mID) {
8763 return this;
8764 }
8765 return null;
8766 }
8767
8768 /**
8769 * {@hide}
8770 * @param tag the tag of the view to be found
8771 * @return the view of specified tag, null if cannot be found
8772 */
8773 protected View findViewWithTagTraversal(Object tag) {
8774 if (tag != null && tag.equals(mTag)) {
8775 return this;
8776 }
8777 return null;
8778 }
8779
8780 /**
8781 * Look for a child view with the given id. If this view has the given
8782 * id, return this view.
8783 *
8784 * @param id The id to search for.
8785 * @return The view that has the given id in the hierarchy or null
8786 */
8787 public final View findViewById(int id) {
8788 if (id < 0) {
8789 return null;
8790 }
8791 return findViewTraversal(id);
8792 }
8793
8794 /**
8795 * Look for a child view with the given tag. If this view has the given
8796 * tag, return this view.
8797 *
8798 * @param tag The tag to search for, using "tag.equals(getTag())".
8799 * @return The View that has the given tag in the hierarchy or null
8800 */
8801 public final View findViewWithTag(Object tag) {
8802 if (tag == null) {
8803 return null;
8804 }
8805 return findViewWithTagTraversal(tag);
8806 }
8807
8808 /**
8809 * Sets the identifier for this view. The identifier does not have to be
8810 * unique in this view's hierarchy. The identifier should be a positive
8811 * number.
8812 *
8813 * @see #NO_ID
8814 * @see #getId
8815 * @see #findViewById
8816 *
8817 * @param id a number used to identify the view
8818 *
8819 * @attr ref android.R.styleable#View_id
8820 */
8821 public void setId(int id) {
8822 mID = id;
8823 }
8824
8825 /**
8826 * {@hide}
8827 *
8828 * @param isRoot true if the view belongs to the root namespace, false
8829 * otherwise
8830 */
8831 public void setIsRootNamespace(boolean isRoot) {
8832 if (isRoot) {
8833 mPrivateFlags |= IS_ROOT_NAMESPACE;
8834 } else {
8835 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
8836 }
8837 }
8838
8839 /**
8840 * {@hide}
8841 *
8842 * @return true if the view belongs to the root namespace, false otherwise
8843 */
8844 public boolean isRootNamespace() {
8845 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
8846 }
8847
8848 /**
8849 * Returns this view's identifier.
8850 *
8851 * @return a positive integer used to identify the view or {@link #NO_ID}
8852 * if the view has no ID
8853 *
8854 * @see #setId
8855 * @see #findViewById
8856 * @attr ref android.R.styleable#View_id
8857 */
8858 @ViewDebug.CapturedViewProperty
8859 public int getId() {
8860 return mID;
8861 }
8862
8863 /**
8864 * Returns this view's tag.
8865 *
8866 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07008867 *
8868 * @see #setTag(Object)
8869 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008870 */
8871 @ViewDebug.ExportedProperty
8872 public Object getTag() {
8873 return mTag;
8874 }
8875
8876 /**
8877 * Sets the tag associated with this view. A tag can be used to mark
8878 * a view in its hierarchy and does not have to be unique within the
8879 * hierarchy. Tags can also be used to store data within a view without
8880 * resorting to another data structure.
8881 *
8882 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07008883 *
8884 * @see #getTag()
8885 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008886 */
8887 public void setTag(final Object tag) {
8888 mTag = tag;
8889 }
8890
8891 /**
Romain Guyd90a3312009-05-06 14:54:28 -07008892 * Returns the tag associated with this view and the specified key.
8893 *
8894 * @param key The key identifying the tag
8895 *
8896 * @return the Object stored in this view as a tag
8897 *
8898 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07008899 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07008900 */
8901 public Object getTag(int key) {
8902 SparseArray<Object> tags = null;
8903 synchronized (sTagsLock) {
8904 if (sTags != null) {
8905 tags = sTags.get(this);
8906 }
8907 }
8908
8909 if (tags != null) return tags.get(key);
8910 return null;
8911 }
8912
8913 /**
8914 * Sets a tag associated with this view and a key. A tag can be used
8915 * to mark a view in its hierarchy and does not have to be unique within
8916 * the hierarchy. Tags can also be used to store data within a view
8917 * without resorting to another data structure.
8918 *
8919 * The specified key should be an id declared in the resources of the
Scott Maindfe5c202010-06-08 15:54:52 -07008920 * application to ensure it is unique (see the <a
8921 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
8922 * Keys identified as belonging to
Romain Guyd90a3312009-05-06 14:54:28 -07008923 * the Android framework or not associated with any package will cause
8924 * an {@link IllegalArgumentException} to be thrown.
8925 *
8926 * @param key The key identifying the tag
8927 * @param tag An Object to tag the view with
8928 *
8929 * @throws IllegalArgumentException If they specified key is not valid
8930 *
8931 * @see #setTag(Object)
8932 * @see #getTag(int)
8933 */
8934 public void setTag(int key, final Object tag) {
8935 // If the package id is 0x00 or 0x01, it's either an undefined package
8936 // or a framework id
8937 if ((key >>> 24) < 2) {
8938 throw new IllegalArgumentException("The key must be an application-specific "
8939 + "resource id.");
8940 }
8941
8942 setTagInternal(this, key, tag);
8943 }
8944
8945 /**
8946 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
8947 * framework id.
8948 *
8949 * @hide
8950 */
8951 public void setTagInternal(int key, Object tag) {
8952 if ((key >>> 24) != 0x1) {
8953 throw new IllegalArgumentException("The key must be a framework-specific "
8954 + "resource id.");
8955 }
8956
Romain Guy8506ab42009-06-11 17:35:47 -07008957 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07008958 }
8959
8960 private static void setTagInternal(View view, int key, Object tag) {
8961 SparseArray<Object> tags = null;
8962 synchronized (sTagsLock) {
8963 if (sTags == null) {
8964 sTags = new WeakHashMap<View, SparseArray<Object>>();
8965 } else {
8966 tags = sTags.get(view);
8967 }
8968 }
8969
8970 if (tags == null) {
8971 tags = new SparseArray<Object>(2);
8972 synchronized (sTagsLock) {
8973 sTags.put(view, tags);
8974 }
8975 }
8976
8977 tags.put(key, tag);
8978 }
8979
8980 /**
Romain Guy13922e02009-05-12 17:56:14 -07008981 * @param consistency The type of consistency. See ViewDebug for more information.
8982 *
8983 * @hide
8984 */
8985 protected boolean dispatchConsistencyCheck(int consistency) {
8986 return onConsistencyCheck(consistency);
8987 }
8988
8989 /**
8990 * Method that subclasses should implement to check their consistency. The type of
8991 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07008992 *
Romain Guy13922e02009-05-12 17:56:14 -07008993 * @param consistency The type of consistency. See ViewDebug for more information.
8994 *
8995 * @throws IllegalStateException if the view is in an inconsistent state.
8996 *
8997 * @hide
8998 */
8999 protected boolean onConsistencyCheck(int consistency) {
9000 boolean result = true;
9001
9002 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
9003 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
9004
9005 if (checkLayout) {
9006 if (getParent() == null) {
9007 result = false;
9008 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9009 "View " + this + " does not have a parent.");
9010 }
9011
9012 if (mAttachInfo == null) {
9013 result = false;
9014 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9015 "View " + this + " is not attached to a window.");
9016 }
9017 }
9018
9019 if (checkDrawing) {
9020 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
9021 // from their draw() method
9022
9023 if ((mPrivateFlags & DRAWN) != DRAWN &&
9024 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
9025 result = false;
9026 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
9027 "View " + this + " was invalidated but its drawing cache is valid.");
9028 }
9029 }
9030
9031 return result;
9032 }
9033
9034 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 * Prints information about this view in the log output, with the tag
9036 * {@link #VIEW_LOG_TAG}.
9037 *
9038 * @hide
9039 */
9040 public void debug() {
9041 debug(0);
9042 }
9043
9044 /**
9045 * Prints information about this view in the log output, with the tag
9046 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
9047 * indentation defined by the <code>depth</code>.
9048 *
9049 * @param depth the indentation level
9050 *
9051 * @hide
9052 */
9053 protected void debug(int depth) {
9054 String output = debugIndent(depth - 1);
9055
9056 output += "+ " + this;
9057 int id = getId();
9058 if (id != -1) {
9059 output += " (id=" + id + ")";
9060 }
9061 Object tag = getTag();
9062 if (tag != null) {
9063 output += " (tag=" + tag + ")";
9064 }
9065 Log.d(VIEW_LOG_TAG, output);
9066
9067 if ((mPrivateFlags & FOCUSED) != 0) {
9068 output = debugIndent(depth) + " FOCUSED";
9069 Log.d(VIEW_LOG_TAG, output);
9070 }
9071
9072 output = debugIndent(depth);
9073 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
9074 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
9075 + "} ";
9076 Log.d(VIEW_LOG_TAG, output);
9077
9078 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
9079 || mPaddingBottom != 0) {
9080 output = debugIndent(depth);
9081 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
9082 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
9083 Log.d(VIEW_LOG_TAG, output);
9084 }
9085
9086 output = debugIndent(depth);
9087 output += "mMeasureWidth=" + mMeasuredWidth +
9088 " mMeasureHeight=" + mMeasuredHeight;
9089 Log.d(VIEW_LOG_TAG, output);
9090
9091 output = debugIndent(depth);
9092 if (mLayoutParams == null) {
9093 output += "BAD! no layout params";
9094 } else {
9095 output = mLayoutParams.debug(output);
9096 }
9097 Log.d(VIEW_LOG_TAG, output);
9098
9099 output = debugIndent(depth);
9100 output += "flags={";
9101 output += View.printFlags(mViewFlags);
9102 output += "}";
9103 Log.d(VIEW_LOG_TAG, output);
9104
9105 output = debugIndent(depth);
9106 output += "privateFlags={";
9107 output += View.printPrivateFlags(mPrivateFlags);
9108 output += "}";
9109 Log.d(VIEW_LOG_TAG, output);
9110 }
9111
9112 /**
9113 * Creates an string of whitespaces used for indentation.
9114 *
9115 * @param depth the indentation level
9116 * @return a String containing (depth * 2 + 3) * 2 white spaces
9117 *
9118 * @hide
9119 */
9120 protected static String debugIndent(int depth) {
9121 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
9122 for (int i = 0; i < (depth * 2) + 3; i++) {
9123 spaces.append(' ').append(' ');
9124 }
9125 return spaces.toString();
9126 }
9127
9128 /**
9129 * <p>Return the offset of the widget's text baseline from the widget's top
9130 * boundary. If this widget does not support baseline alignment, this
9131 * method returns -1. </p>
9132 *
9133 * @return the offset of the baseline within the widget's bounds or -1
9134 * if baseline alignment is not supported
9135 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07009136 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009137 public int getBaseline() {
9138 return -1;
9139 }
9140
9141 /**
9142 * Call this when something has changed which has invalidated the
9143 * layout of this view. This will schedule a layout pass of the view
9144 * tree.
9145 */
9146 public void requestLayout() {
9147 if (ViewDebug.TRACE_HIERARCHY) {
9148 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
9149 }
9150
9151 mPrivateFlags |= FORCE_LAYOUT;
9152
9153 if (mParent != null && !mParent.isLayoutRequested()) {
9154 mParent.requestLayout();
9155 }
9156 }
9157
9158 /**
9159 * Forces this view to be laid out during the next layout pass.
9160 * This method does not call requestLayout() or forceLayout()
9161 * on the parent.
9162 */
9163 public void forceLayout() {
9164 mPrivateFlags |= FORCE_LAYOUT;
9165 }
9166
9167 /**
9168 * <p>
9169 * This is called to find out how big a view should be. The parent
9170 * supplies constraint information in the width and height parameters.
9171 * </p>
9172 *
9173 * <p>
9174 * The actual mesurement work of a view is performed in
9175 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
9176 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
9177 * </p>
9178 *
9179 *
9180 * @param widthMeasureSpec Horizontal space requirements as imposed by the
9181 * parent
9182 * @param heightMeasureSpec Vertical space requirements as imposed by the
9183 * parent
9184 *
9185 * @see #onMeasure(int, int)
9186 */
9187 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
9188 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
9189 widthMeasureSpec != mOldWidthMeasureSpec ||
9190 heightMeasureSpec != mOldHeightMeasureSpec) {
9191
9192 // first clears the measured dimension flag
9193 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
9194
9195 if (ViewDebug.TRACE_HIERARCHY) {
9196 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
9197 }
9198
9199 // measure ourselves, this should set the measured dimension flag back
9200 onMeasure(widthMeasureSpec, heightMeasureSpec);
9201
9202 // flag not set, setMeasuredDimension() was not invoked, we raise
9203 // an exception to warn the developer
9204 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
9205 throw new IllegalStateException("onMeasure() did not set the"
9206 + " measured dimension by calling"
9207 + " setMeasuredDimension()");
9208 }
9209
9210 mPrivateFlags |= LAYOUT_REQUIRED;
9211 }
9212
9213 mOldWidthMeasureSpec = widthMeasureSpec;
9214 mOldHeightMeasureSpec = heightMeasureSpec;
9215 }
9216
9217 /**
9218 * <p>
9219 * Measure the view and its content to determine the measured width and the
9220 * measured height. This method is invoked by {@link #measure(int, int)} and
9221 * should be overriden by subclasses to provide accurate and efficient
9222 * measurement of their contents.
9223 * </p>
9224 *
9225 * <p>
9226 * <strong>CONTRACT:</strong> When overriding this method, you
9227 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
9228 * measured width and height of this view. Failure to do so will trigger an
9229 * <code>IllegalStateException</code>, thrown by
9230 * {@link #measure(int, int)}. Calling the superclass'
9231 * {@link #onMeasure(int, int)} is a valid use.
9232 * </p>
9233 *
9234 * <p>
9235 * The base class implementation of measure defaults to the background size,
9236 * unless a larger size is allowed by the MeasureSpec. Subclasses should
9237 * override {@link #onMeasure(int, int)} to provide better measurements of
9238 * their content.
9239 * </p>
9240 *
9241 * <p>
9242 * If this method is overridden, it is the subclass's responsibility to make
9243 * sure the measured height and width are at least the view's minimum height
9244 * and width ({@link #getSuggestedMinimumHeight()} and
9245 * {@link #getSuggestedMinimumWidth()}).
9246 * </p>
9247 *
9248 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
9249 * The requirements are encoded with
9250 * {@link android.view.View.MeasureSpec}.
9251 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
9252 * The requirements are encoded with
9253 * {@link android.view.View.MeasureSpec}.
9254 *
9255 * @see #getMeasuredWidth()
9256 * @see #getMeasuredHeight()
9257 * @see #setMeasuredDimension(int, int)
9258 * @see #getSuggestedMinimumHeight()
9259 * @see #getSuggestedMinimumWidth()
9260 * @see android.view.View.MeasureSpec#getMode(int)
9261 * @see android.view.View.MeasureSpec#getSize(int)
9262 */
9263 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
9264 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
9265 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
9266 }
9267
9268 /**
9269 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
9270 * measured width and measured height. Failing to do so will trigger an
9271 * exception at measurement time.</p>
9272 *
9273 * @param measuredWidth the measured width of this view
9274 * @param measuredHeight the measured height of this view
9275 */
9276 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
9277 mMeasuredWidth = measuredWidth;
9278 mMeasuredHeight = measuredHeight;
9279
9280 mPrivateFlags |= MEASURED_DIMENSION_SET;
9281 }
9282
9283 /**
9284 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
9285 * Will take the desired size, unless a different size is imposed by the constraints.
9286 *
9287 * @param size How big the view wants to be
9288 * @param measureSpec Constraints imposed by the parent
9289 * @return The size this view should be.
9290 */
9291 public static int resolveSize(int size, int measureSpec) {
9292 int result = size;
9293 int specMode = MeasureSpec.getMode(measureSpec);
9294 int specSize = MeasureSpec.getSize(measureSpec);
9295 switch (specMode) {
9296 case MeasureSpec.UNSPECIFIED:
9297 result = size;
9298 break;
9299 case MeasureSpec.AT_MOST:
9300 result = Math.min(size, specSize);
9301 break;
9302 case MeasureSpec.EXACTLY:
9303 result = specSize;
9304 break;
9305 }
9306 return result;
9307 }
9308
9309 /**
9310 * Utility to return a default size. Uses the supplied size if the
9311 * MeasureSpec imposed no contraints. Will get larger if allowed
9312 * by the MeasureSpec.
9313 *
9314 * @param size Default size for this view
9315 * @param measureSpec Constraints imposed by the parent
9316 * @return The size this view should be.
9317 */
9318 public static int getDefaultSize(int size, int measureSpec) {
9319 int result = size;
9320 int specMode = MeasureSpec.getMode(measureSpec);
9321 int specSize = MeasureSpec.getSize(measureSpec);
9322
9323 switch (specMode) {
9324 case MeasureSpec.UNSPECIFIED:
9325 result = size;
9326 break;
9327 case MeasureSpec.AT_MOST:
9328 case MeasureSpec.EXACTLY:
9329 result = specSize;
9330 break;
9331 }
9332 return result;
9333 }
9334
9335 /**
9336 * Returns the suggested minimum height that the view should use. This
9337 * returns the maximum of the view's minimum height
9338 * and the background's minimum height
9339 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
9340 * <p>
9341 * When being used in {@link #onMeasure(int, int)}, the caller should still
9342 * ensure the returned height is within the requirements of the parent.
9343 *
9344 * @return The suggested minimum height of the view.
9345 */
9346 protected int getSuggestedMinimumHeight() {
9347 int suggestedMinHeight = mMinHeight;
9348
9349 if (mBGDrawable != null) {
9350 final int bgMinHeight = mBGDrawable.getMinimumHeight();
9351 if (suggestedMinHeight < bgMinHeight) {
9352 suggestedMinHeight = bgMinHeight;
9353 }
9354 }
9355
9356 return suggestedMinHeight;
9357 }
9358
9359 /**
9360 * Returns the suggested minimum width that the view should use. This
9361 * returns the maximum of the view's minimum width)
9362 * and the background's minimum width
9363 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
9364 * <p>
9365 * When being used in {@link #onMeasure(int, int)}, the caller should still
9366 * ensure the returned width is within the requirements of the parent.
9367 *
9368 * @return The suggested minimum width of the view.
9369 */
9370 protected int getSuggestedMinimumWidth() {
9371 int suggestedMinWidth = mMinWidth;
9372
9373 if (mBGDrawable != null) {
9374 final int bgMinWidth = mBGDrawable.getMinimumWidth();
9375 if (suggestedMinWidth < bgMinWidth) {
9376 suggestedMinWidth = bgMinWidth;
9377 }
9378 }
9379
9380 return suggestedMinWidth;
9381 }
9382
9383 /**
9384 * Sets the minimum height of the view. It is not guaranteed the view will
9385 * be able to achieve this minimum height (for example, if its parent layout
9386 * constrains it with less available height).
9387 *
9388 * @param minHeight The minimum height the view will try to be.
9389 */
9390 public void setMinimumHeight(int minHeight) {
9391 mMinHeight = minHeight;
9392 }
9393
9394 /**
9395 * Sets the minimum width of the view. It is not guaranteed the view will
9396 * be able to achieve this minimum width (for example, if its parent layout
9397 * constrains it with less available width).
9398 *
9399 * @param minWidth The minimum width the view will try to be.
9400 */
9401 public void setMinimumWidth(int minWidth) {
9402 mMinWidth = minWidth;
9403 }
9404
9405 /**
9406 * Get the animation currently associated with this view.
9407 *
9408 * @return The animation that is currently playing or
9409 * scheduled to play for this view.
9410 */
9411 public Animation getAnimation() {
9412 return mCurrentAnimation;
9413 }
9414
9415 /**
9416 * Start the specified animation now.
9417 *
9418 * @param animation the animation to start now
9419 */
9420 public void startAnimation(Animation animation) {
9421 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
9422 setAnimation(animation);
9423 invalidate();
9424 }
9425
9426 /**
9427 * Cancels any animations for this view.
9428 */
9429 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08009430 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08009431 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08009432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009433 mCurrentAnimation = null;
9434 }
9435
9436 /**
9437 * Sets the next animation to play for this view.
9438 * If you want the animation to play immediately, use
9439 * startAnimation. This method provides allows fine-grained
9440 * control over the start time and invalidation, but you
9441 * must make sure that 1) the animation has a start time set, and
9442 * 2) the view will be invalidated when the animation is supposed to
9443 * start.
9444 *
9445 * @param animation The next animation, or null.
9446 */
9447 public void setAnimation(Animation animation) {
9448 mCurrentAnimation = animation;
9449 if (animation != null) {
9450 animation.reset();
9451 }
9452 }
9453
9454 /**
9455 * Invoked by a parent ViewGroup to notify the start of the animation
9456 * currently associated with this view. If you override this method,
9457 * always call super.onAnimationStart();
9458 *
9459 * @see #setAnimation(android.view.animation.Animation)
9460 * @see #getAnimation()
9461 */
9462 protected void onAnimationStart() {
9463 mPrivateFlags |= ANIMATION_STARTED;
9464 }
9465
9466 /**
9467 * Invoked by a parent ViewGroup to notify the end of the animation
9468 * currently associated with this view. If you override this method,
9469 * always call super.onAnimationEnd();
9470 *
9471 * @see #setAnimation(android.view.animation.Animation)
9472 * @see #getAnimation()
9473 */
9474 protected void onAnimationEnd() {
9475 mPrivateFlags &= ~ANIMATION_STARTED;
9476 }
9477
9478 /**
9479 * Invoked if there is a Transform that involves alpha. Subclass that can
9480 * draw themselves with the specified alpha should return true, and then
9481 * respect that alpha when their onDraw() is called. If this returns false
9482 * then the view may be redirected to draw into an offscreen buffer to
9483 * fulfill the request, which will look fine, but may be slower than if the
9484 * subclass handles it internally. The default implementation returns false.
9485 *
9486 * @param alpha The alpha (0..255) to apply to the view's drawing
9487 * @return true if the view can draw with the specified alpha.
9488 */
9489 protected boolean onSetAlpha(int alpha) {
9490 return false;
9491 }
9492
9493 /**
9494 * This is used by the RootView to perform an optimization when
9495 * the view hierarchy contains one or several SurfaceView.
9496 * SurfaceView is always considered transparent, but its children are not,
9497 * therefore all View objects remove themselves from the global transparent
9498 * region (passed as a parameter to this function).
9499 *
9500 * @param region The transparent region for this ViewRoot (window).
9501 *
9502 * @return Returns true if the effective visibility of the view at this
9503 * point is opaque, regardless of the transparent region; returns false
9504 * if it is possible for underlying windows to be seen behind the view.
9505 *
9506 * {@hide}
9507 */
9508 public boolean gatherTransparentRegion(Region region) {
9509 final AttachInfo attachInfo = mAttachInfo;
9510 if (region != null && attachInfo != null) {
9511 final int pflags = mPrivateFlags;
9512 if ((pflags & SKIP_DRAW) == 0) {
9513 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
9514 // remove it from the transparent region.
9515 final int[] location = attachInfo.mTransparentLocation;
9516 getLocationInWindow(location);
9517 region.op(location[0], location[1], location[0] + mRight - mLeft,
9518 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
9519 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
9520 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
9521 // exists, so we remove the background drawable's non-transparent
9522 // parts from this transparent region.
9523 applyDrawableToTransparentRegion(mBGDrawable, region);
9524 }
9525 }
9526 return true;
9527 }
9528
9529 /**
9530 * Play a sound effect for this view.
9531 *
9532 * <p>The framework will play sound effects for some built in actions, such as
9533 * clicking, but you may wish to play these effects in your widget,
9534 * for instance, for internal navigation.
9535 *
9536 * <p>The sound effect will only be played if sound effects are enabled by the user, and
9537 * {@link #isSoundEffectsEnabled()} is true.
9538 *
9539 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
9540 */
9541 public void playSoundEffect(int soundConstant) {
9542 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
9543 return;
9544 }
9545 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
9546 }
9547
9548 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009549 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009550 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009551 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009552 *
9553 * <p>The framework will provide haptic feedback for some built in actions,
9554 * such as long presses, but you may wish to provide feedback for your
9555 * own widget.
9556 *
9557 * <p>The feedback will only be performed if
9558 * {@link #isHapticFeedbackEnabled()} is true.
9559 *
9560 * @param feedbackConstant One of the constants defined in
9561 * {@link HapticFeedbackConstants}
9562 */
9563 public boolean performHapticFeedback(int feedbackConstant) {
9564 return performHapticFeedback(feedbackConstant, 0);
9565 }
9566
9567 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009568 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07009569 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07009570 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009571 *
9572 * @param feedbackConstant One of the constants defined in
9573 * {@link HapticFeedbackConstants}
9574 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
9575 */
9576 public boolean performHapticFeedback(int feedbackConstant, int flags) {
9577 if (mAttachInfo == null) {
9578 return false;
9579 }
Romain Guy812ccbe2010-06-01 14:07:24 -07009580 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009581 && !isHapticFeedbackEnabled()) {
9582 return false;
9583 }
Romain Guy812ccbe2010-06-01 14:07:24 -07009584 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
9585 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009586 }
9587
9588 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -07009589 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
9590 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -07009591 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -07009592 */
9593 public void onCloseSystemDialogs(String reason) {
9594 }
9595
9596 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009597 * Given a Drawable whose bounds have been set to draw into this view,
9598 * update a Region being computed for {@link #gatherTransparentRegion} so
9599 * that any non-transparent parts of the Drawable are removed from the
9600 * given transparent region.
9601 *
9602 * @param dr The Drawable whose transparency is to be applied to the region.
9603 * @param region A Region holding the current transparency information,
9604 * where any parts of the region that are set are considered to be
9605 * transparent. On return, this region will be modified to have the
9606 * transparency information reduced by the corresponding parts of the
9607 * Drawable that are not transparent.
9608 * {@hide}
9609 */
9610 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
9611 if (DBG) {
9612 Log.i("View", "Getting transparent region for: " + this);
9613 }
9614 final Region r = dr.getTransparentRegion();
9615 final Rect db = dr.getBounds();
9616 final AttachInfo attachInfo = mAttachInfo;
9617 if (r != null && attachInfo != null) {
9618 final int w = getRight()-getLeft();
9619 final int h = getBottom()-getTop();
9620 if (db.left > 0) {
9621 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
9622 r.op(0, 0, db.left, h, Region.Op.UNION);
9623 }
9624 if (db.right < w) {
9625 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
9626 r.op(db.right, 0, w, h, Region.Op.UNION);
9627 }
9628 if (db.top > 0) {
9629 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
9630 r.op(0, 0, w, db.top, Region.Op.UNION);
9631 }
9632 if (db.bottom < h) {
9633 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
9634 r.op(0, db.bottom, w, h, Region.Op.UNION);
9635 }
9636 final int[] location = attachInfo.mTransparentLocation;
9637 getLocationInWindow(location);
9638 r.translate(location[0], location[1]);
9639 region.op(r, Region.Op.INTERSECT);
9640 } else {
9641 region.op(db, Region.Op.DIFFERENCE);
9642 }
9643 }
9644
Adam Powelle14579b2009-12-16 18:39:52 -08009645 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009646 mHasPerformedLongPress = false;
9647
9648 if (mPendingCheckForLongPress == null) {
9649 mPendingCheckForLongPress = new CheckForLongPress();
9650 }
9651 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -08009652 postDelayed(mPendingCheckForLongPress,
9653 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009654 }
9655
Romain Guy812ccbe2010-06-01 14:07:24 -07009656 private static int[] stateSetUnion(final int[] stateSet1, final int[] stateSet2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009657 final int stateSet1Length = stateSet1.length;
9658 final int stateSet2Length = stateSet2.length;
9659 final int[] newSet = new int[stateSet1Length + stateSet2Length];
9660 int k = 0;
9661 int i = 0;
9662 int j = 0;
9663 // This is a merge of the two input state sets and assumes that the
9664 // input sets are sorted by the order imposed by ViewDrawableStates.
9665 for (int viewState : R.styleable.ViewDrawableStates) {
9666 if (i < stateSet1Length && stateSet1[i] == viewState) {
9667 newSet[k++] = viewState;
9668 i++;
9669 } else if (j < stateSet2Length && stateSet2[j] == viewState) {
9670 newSet[k++] = viewState;
9671 j++;
9672 }
9673 if (k > 1) {
9674 assert(newSet[k - 1] > newSet[k - 2]);
9675 }
9676 }
9677 return newSet;
9678 }
9679
9680 /**
9681 * Inflate a view from an XML resource. This convenience method wraps the {@link
9682 * LayoutInflater} class, which provides a full range of options for view inflation.
9683 *
9684 * @param context The Context object for your activity or application.
9685 * @param resource The resource ID to inflate
9686 * @param root A view group that will be the parent. Used to properly inflate the
9687 * layout_* parameters.
9688 * @see LayoutInflater
9689 */
9690 public static View inflate(Context context, int resource, ViewGroup root) {
9691 LayoutInflater factory = LayoutInflater.from(context);
9692 return factory.inflate(resource, root);
9693 }
Romain Guy33e72ae2010-07-17 12:40:29 -07009694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009695 /**
9696 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
9697 * Each MeasureSpec represents a requirement for either the width or the height.
9698 * A MeasureSpec is comprised of a size and a mode. There are three possible
9699 * modes:
9700 * <dl>
9701 * <dt>UNSPECIFIED</dt>
9702 * <dd>
9703 * The parent has not imposed any constraint on the child. It can be whatever size
9704 * it wants.
9705 * </dd>
9706 *
9707 * <dt>EXACTLY</dt>
9708 * <dd>
9709 * The parent has determined an exact size for the child. The child is going to be
9710 * given those bounds regardless of how big it wants to be.
9711 * </dd>
9712 *
9713 * <dt>AT_MOST</dt>
9714 * <dd>
9715 * The child can be as large as it wants up to the specified size.
9716 * </dd>
9717 * </dl>
9718 *
9719 * MeasureSpecs are implemented as ints to reduce object allocation. This class
9720 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
9721 */
9722 public static class MeasureSpec {
9723 private static final int MODE_SHIFT = 30;
9724 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
9725
9726 /**
9727 * Measure specification mode: The parent has not imposed any constraint
9728 * on the child. It can be whatever size it wants.
9729 */
9730 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
9731
9732 /**
9733 * Measure specification mode: The parent has determined an exact size
9734 * for the child. The child is going to be given those bounds regardless
9735 * of how big it wants to be.
9736 */
9737 public static final int EXACTLY = 1 << MODE_SHIFT;
9738
9739 /**
9740 * Measure specification mode: The child can be as large as it wants up
9741 * to the specified size.
9742 */
9743 public static final int AT_MOST = 2 << MODE_SHIFT;
9744
9745 /**
9746 * Creates a measure specification based on the supplied size and mode.
9747 *
9748 * The mode must always be one of the following:
9749 * <ul>
9750 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
9751 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
9752 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
9753 * </ul>
9754 *
9755 * @param size the size of the measure specification
9756 * @param mode the mode of the measure specification
9757 * @return the measure specification based on size and mode
9758 */
9759 public static int makeMeasureSpec(int size, int mode) {
9760 return size + mode;
9761 }
9762
9763 /**
9764 * Extracts the mode from the supplied measure specification.
9765 *
9766 * @param measureSpec the measure specification to extract the mode from
9767 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
9768 * {@link android.view.View.MeasureSpec#AT_MOST} or
9769 * {@link android.view.View.MeasureSpec#EXACTLY}
9770 */
9771 public static int getMode(int measureSpec) {
9772 return (measureSpec & MODE_MASK);
9773 }
9774
9775 /**
9776 * Extracts the size from the supplied measure specification.
9777 *
9778 * @param measureSpec the measure specification to extract the size from
9779 * @return the size in pixels defined in the supplied measure specification
9780 */
9781 public static int getSize(int measureSpec) {
9782 return (measureSpec & ~MODE_MASK);
9783 }
9784
9785 /**
9786 * Returns a String representation of the specified measure
9787 * specification.
9788 *
9789 * @param measureSpec the measure specification to convert to a String
9790 * @return a String with the following format: "MeasureSpec: MODE SIZE"
9791 */
9792 public static String toString(int measureSpec) {
9793 int mode = getMode(measureSpec);
9794 int size = getSize(measureSpec);
9795
9796 StringBuilder sb = new StringBuilder("MeasureSpec: ");
9797
9798 if (mode == UNSPECIFIED)
9799 sb.append("UNSPECIFIED ");
9800 else if (mode == EXACTLY)
9801 sb.append("EXACTLY ");
9802 else if (mode == AT_MOST)
9803 sb.append("AT_MOST ");
9804 else
9805 sb.append(mode).append(" ");
9806
9807 sb.append(size);
9808 return sb.toString();
9809 }
9810 }
9811
9812 class CheckForLongPress implements Runnable {
9813
9814 private int mOriginalWindowAttachCount;
9815
9816 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -07009817 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009818 && mOriginalWindowAttachCount == mWindowAttachCount) {
9819 if (performLongClick()) {
9820 mHasPerformedLongPress = true;
9821 }
9822 }
9823 }
9824
9825 public void rememberWindowAttachCount() {
9826 mOriginalWindowAttachCount = mWindowAttachCount;
9827 }
9828 }
Adam Powelle14579b2009-12-16 18:39:52 -08009829
9830 private final class CheckForTap implements Runnable {
9831 public void run() {
9832 mPrivateFlags &= ~PREPRESSED;
9833 mPrivateFlags |= PRESSED;
9834 refreshDrawableState();
9835 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
9836 postCheckForLongClick(ViewConfiguration.getTapTimeout());
9837 }
9838 }
9839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009840
Adam Powella35d7682010-03-12 14:48:13 -08009841 private final class PerformClick implements Runnable {
9842 public void run() {
9843 performClick();
9844 }
9845 }
9846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009847 /**
9848 * Interface definition for a callback to be invoked when a key event is
9849 * dispatched to this view. The callback will be invoked before the key
9850 * event is given to the view.
9851 */
9852 public interface OnKeyListener {
9853 /**
9854 * Called when a key is dispatched to a view. This allows listeners to
9855 * get a chance to respond before the target view.
9856 *
9857 * @param v The view the key has been dispatched to.
9858 * @param keyCode The code for the physical key that was pressed
9859 * @param event The KeyEvent object containing full information about
9860 * the event.
9861 * @return True if the listener has consumed the event, false otherwise.
9862 */
9863 boolean onKey(View v, int keyCode, KeyEvent event);
9864 }
9865
9866 /**
9867 * Interface definition for a callback to be invoked when a touch event is
9868 * dispatched to this view. The callback will be invoked before the touch
9869 * event is given to the view.
9870 */
9871 public interface OnTouchListener {
9872 /**
9873 * Called when a touch event is dispatched to a view. This allows listeners to
9874 * get a chance to respond before the target view.
9875 *
9876 * @param v The view the touch event has been dispatched to.
9877 * @param event The MotionEvent object containing full information about
9878 * the event.
9879 * @return True if the listener has consumed the event, false otherwise.
9880 */
9881 boolean onTouch(View v, MotionEvent event);
9882 }
9883
9884 /**
9885 * Interface definition for a callback to be invoked when a view has been clicked and held.
9886 */
9887 public interface OnLongClickListener {
9888 /**
9889 * Called when a view has been clicked and held.
9890 *
9891 * @param v The view that was clicked and held.
9892 *
9893 * return True if the callback consumed the long click, false otherwise
9894 */
9895 boolean onLongClick(View v);
9896 }
9897
9898 /**
9899 * Interface definition for a callback to be invoked when the focus state of
9900 * a view changed.
9901 */
9902 public interface OnFocusChangeListener {
9903 /**
9904 * Called when the focus state of a view has changed.
9905 *
9906 * @param v The view whose state has changed.
9907 * @param hasFocus The new focus state of v.
9908 */
9909 void onFocusChange(View v, boolean hasFocus);
9910 }
9911
9912 /**
9913 * Interface definition for a callback to be invoked when a view is clicked.
9914 */
9915 public interface OnClickListener {
9916 /**
9917 * Called when a view has been clicked.
9918 *
9919 * @param v The view that was clicked.
9920 */
9921 void onClick(View v);
9922 }
9923
9924 /**
9925 * Interface definition for a callback to be invoked when the context menu
9926 * for this view is being built.
9927 */
9928 public interface OnCreateContextMenuListener {
9929 /**
9930 * Called when the context menu for this view is being built. It is not
9931 * safe to hold onto the menu after this method returns.
9932 *
9933 * @param menu The context menu that is being built
9934 * @param v The view for which the context menu is being built
9935 * @param menuInfo Extra information about the item for which the
9936 * context menu should be shown. This information will vary
9937 * depending on the class of v.
9938 */
9939 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
9940 }
9941
9942 private final class UnsetPressedState implements Runnable {
9943 public void run() {
9944 setPressed(false);
9945 }
9946 }
9947
9948 /**
9949 * Base class for derived classes that want to save and restore their own
9950 * state in {@link android.view.View#onSaveInstanceState()}.
9951 */
9952 public static class BaseSavedState extends AbsSavedState {
9953 /**
9954 * Constructor used when reading from a parcel. Reads the state of the superclass.
9955 *
9956 * @param source
9957 */
9958 public BaseSavedState(Parcel source) {
9959 super(source);
9960 }
9961
9962 /**
9963 * Constructor called by derived classes when creating their SavedState objects
9964 *
9965 * @param superState The state of the superclass of this view
9966 */
9967 public BaseSavedState(Parcelable superState) {
9968 super(superState);
9969 }
9970
9971 public static final Parcelable.Creator<BaseSavedState> CREATOR =
9972 new Parcelable.Creator<BaseSavedState>() {
9973 public BaseSavedState createFromParcel(Parcel in) {
9974 return new BaseSavedState(in);
9975 }
9976
9977 public BaseSavedState[] newArray(int size) {
9978 return new BaseSavedState[size];
9979 }
9980 };
9981 }
9982
9983 /**
9984 * A set of information given to a view when it is attached to its parent
9985 * window.
9986 */
9987 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009988 interface Callbacks {
9989 void playSoundEffect(int effectId);
9990 boolean performHapticFeedback(int effectId, boolean always);
9991 }
9992
9993 /**
9994 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
9995 * to a Handler. This class contains the target (View) to invalidate and
9996 * the coordinates of the dirty rectangle.
9997 *
9998 * For performance purposes, this class also implements a pool of up to
9999 * POOL_LIMIT objects that get reused. This reduces memory allocations
10000 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010001 */
Romain Guyd928d682009-03-31 17:52:16 -070010002 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010003 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -070010004 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
10005 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -070010006 public InvalidateInfo newInstance() {
10007 return new InvalidateInfo();
10008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010009
Romain Guyd928d682009-03-31 17:52:16 -070010010 public void onAcquired(InvalidateInfo element) {
10011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010012
Romain Guyd928d682009-03-31 17:52:16 -070010013 public void onReleased(InvalidateInfo element) {
10014 }
10015 }, POOL_LIMIT)
10016 );
10017
10018 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010019
10020 View target;
10021
10022 int left;
10023 int top;
10024 int right;
10025 int bottom;
10026
Romain Guyd928d682009-03-31 17:52:16 -070010027 public void setNextPoolable(InvalidateInfo element) {
10028 mNext = element;
10029 }
10030
10031 public InvalidateInfo getNextPoolable() {
10032 return mNext;
10033 }
10034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010035 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -070010036 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010037 }
10038
10039 void release() {
Romain Guyd928d682009-03-31 17:52:16 -070010040 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010041 }
10042 }
10043
10044 final IWindowSession mSession;
10045
10046 final IWindow mWindow;
10047
10048 final IBinder mWindowToken;
10049
10050 final Callbacks mRootCallbacks;
10051
10052 /**
10053 * The top view of the hierarchy.
10054 */
10055 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -070010056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010057 IBinder mPanelParentWindowToken;
10058 Surface mSurface;
10059
10060 /**
Romain Guy8506ab42009-06-11 17:35:47 -070010061 * Scale factor used by the compatibility mode
10062 */
10063 float mApplicationScale;
10064
10065 /**
10066 * Indicates whether the application is in compatibility mode
10067 */
10068 boolean mScalingRequired;
10069
10070 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010071 * Left position of this view's window
10072 */
10073 int mWindowLeft;
10074
10075 /**
10076 * Top position of this view's window
10077 */
10078 int mWindowTop;
10079
10080 /**
Romain Guy35b38ce2009-10-07 13:38:55 -070010081 * Indicates whether the window is translucent/transparent
10082 */
10083 boolean mTranslucentWindow;
10084
10085 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010086 * For windows that are full-screen but using insets to layout inside
10087 * of the screen decorations, these are the current insets for the
10088 * content of the window.
10089 */
10090 final Rect mContentInsets = new Rect();
10091
10092 /**
10093 * For windows that are full-screen but using insets to layout inside
10094 * of the screen decorations, these are the current insets for the
10095 * actual visible parts of the window.
10096 */
10097 final Rect mVisibleInsets = new Rect();
10098
10099 /**
10100 * The internal insets given by this window. This value is
10101 * supplied by the client (through
10102 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
10103 * be given to the window manager when changed to be used in laying
10104 * out windows behind it.
10105 */
10106 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
10107 = new ViewTreeObserver.InternalInsetsInfo();
10108
10109 /**
10110 * All views in the window's hierarchy that serve as scroll containers,
10111 * used to determine if the window can be resized or must be panned
10112 * to adjust for a soft input area.
10113 */
10114 final ArrayList<View> mScrollContainers = new ArrayList<View>();
10115
Dianne Hackborn83fe3f52009-09-12 23:38:30 -070010116 final KeyEvent.DispatcherState mKeyDispatchState
10117 = new KeyEvent.DispatcherState();
10118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010119 /**
10120 * Indicates whether the view's window currently has the focus.
10121 */
10122 boolean mHasWindowFocus;
10123
10124 /**
10125 * The current visibility of the window.
10126 */
10127 int mWindowVisibility;
10128
10129 /**
10130 * Indicates the time at which drawing started to occur.
10131 */
10132 long mDrawingTime;
10133
10134 /**
Romain Guy5bcdff42009-05-14 21:27:18 -070010135 * Indicates whether or not ignoring the DIRTY_MASK flags.
10136 */
10137 boolean mIgnoreDirtyState;
10138
10139 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010140 * Indicates whether the view's window is currently in touch mode.
10141 */
10142 boolean mInTouchMode;
10143
10144 /**
10145 * Indicates that ViewRoot should trigger a global layout change
10146 * the next time it performs a traversal
10147 */
10148 boolean mRecomputeGlobalAttributes;
10149
10150 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010151 * Set during a traveral if any views want to keep the screen on.
10152 */
10153 boolean mKeepScreenOn;
10154
10155 /**
10156 * Set if the visibility of any views has changed.
10157 */
10158 boolean mViewVisibilityChanged;
10159
10160 /**
10161 * Set to true if a view has been scrolled.
10162 */
10163 boolean mViewScrollChanged;
10164
10165 /**
10166 * Global to the view hierarchy used as a temporary for dealing with
10167 * x/y points in the transparent region computations.
10168 */
10169 final int[] mTransparentLocation = new int[2];
10170
10171 /**
10172 * Global to the view hierarchy used as a temporary for dealing with
10173 * x/y points in the ViewGroup.invalidateChild implementation.
10174 */
10175 final int[] mInvalidateChildLocation = new int[2];
10176
Chet Haasec3aa3612010-06-17 08:50:37 -070010177
10178 /**
10179 * Global to the view hierarchy used as a temporary for dealing with
10180 * x/y location when view is transformed.
10181 */
10182 final float[] mTmpTransformLocation = new float[2];
10183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010184 /**
10185 * The view tree observer used to dispatch global events like
10186 * layout, pre-draw, touch mode change, etc.
10187 */
10188 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
10189
10190 /**
10191 * A Canvas used by the view hierarchy to perform bitmap caching.
10192 */
10193 Canvas mCanvas;
10194
10195 /**
10196 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
10197 * handler can be used to pump events in the UI events queue.
10198 */
10199 final Handler mHandler;
10200
10201 /**
10202 * Identifier for messages requesting the view to be invalidated.
10203 * Such messages should be sent to {@link #mHandler}.
10204 */
10205 static final int INVALIDATE_MSG = 0x1;
10206
10207 /**
10208 * Identifier for messages requesting the view to invalidate a region.
10209 * Such messages should be sent to {@link #mHandler}.
10210 */
10211 static final int INVALIDATE_RECT_MSG = 0x2;
10212
10213 /**
10214 * Temporary for use in computing invalidate rectangles while
10215 * calling up the hierarchy.
10216 */
10217 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -070010218
10219 /**
Chet Haasec3aa3612010-06-17 08:50:37 -070010220 * Temporary for use in computing hit areas with transformed views
10221 */
10222 final RectF mTmpTransformRect = new RectF();
10223
10224 /**
svetoslavganov75986cf2009-05-14 22:28:01 -070010225 * Temporary list for use in collecting focusable descendents of a view.
10226 */
10227 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
10228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010229 /**
10230 * Creates a new set of attachment information with the specified
10231 * events handler and thread.
10232 *
10233 * @param handler the events handler the view must use
10234 */
10235 AttachInfo(IWindowSession session, IWindow window,
10236 Handler handler, Callbacks effectPlayer) {
10237 mSession = session;
10238 mWindow = window;
10239 mWindowToken = window.asBinder();
10240 mHandler = handler;
10241 mRootCallbacks = effectPlayer;
10242 }
10243 }
10244
10245 /**
10246 * <p>ScrollabilityCache holds various fields used by a View when scrolling
10247 * is supported. This avoids keeping too many unused fields in most
10248 * instances of View.</p>
10249 */
Mike Cleronf116bf82009-09-27 19:14:12 -070010250 private static class ScrollabilityCache implements Runnable {
10251
10252 /**
10253 * Scrollbars are not visible
10254 */
10255 public static final int OFF = 0;
10256
10257 /**
10258 * Scrollbars are visible
10259 */
10260 public static final int ON = 1;
10261
10262 /**
10263 * Scrollbars are fading away
10264 */
10265 public static final int FADING = 2;
10266
10267 public boolean fadeScrollBars;
10268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010269 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -070010270 public int scrollBarDefaultDelayBeforeFade;
10271 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010272
10273 public int scrollBarSize;
10274 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -070010275 public float[] interpolatorValues;
10276 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010277
10278 public final Paint paint;
10279 public final Matrix matrix;
10280 public Shader shader;
10281
Mike Cleronf116bf82009-09-27 19:14:12 -070010282 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
10283
Romain Guy8fb95422010-08-17 18:38:51 -070010284 private final float[] mOpaque = { 255.0f };
10285 private final float[] mTransparent = { 0.0f };
Mike Cleronf116bf82009-09-27 19:14:12 -070010286
10287 /**
10288 * When fading should start. This time moves into the future every time
10289 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
10290 */
10291 public long fadeStartTime;
10292
10293
10294 /**
10295 * The current state of the scrollbars: ON, OFF, or FADING
10296 */
10297 public int state = OFF;
10298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010299 private int mLastColor;
10300
Mike Cleronf116bf82009-09-27 19:14:12 -070010301 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010302 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
10303 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -070010304 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
10305 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010306
10307 paint = new Paint();
10308 matrix = new Matrix();
10309 // use use a height of 1, and then wack the matrix each time we
10310 // actually use it.
10311 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010313 paint.setShader(shader);
10314 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -070010315 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010316 }
Romain Guy8506ab42009-06-11 17:35:47 -070010317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010318 public void setFadeColor(int color) {
10319 if (color != 0 && color != mLastColor) {
10320 mLastColor = color;
10321 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -070010322
Romain Guye55e1a72009-08-27 10:42:26 -070010323 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
10324 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -070010325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010326 paint.setShader(shader);
10327 // Restore the default transfer mode (src_over)
10328 paint.setXfermode(null);
10329 }
10330 }
Mike Cleronf116bf82009-09-27 19:14:12 -070010331
10332 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -070010333 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -070010334 if (now >= fadeStartTime) {
10335
10336 // the animation fades the scrollbars out by changing
10337 // the opacity (alpha) from fully opaque to fully
10338 // transparent
10339 int nextFrame = (int) now;
10340 int framesCount = 0;
10341
10342 Interpolator interpolator = scrollBarInterpolator;
10343
10344 // Start opaque
10345 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
10346
10347 // End transparent
10348 nextFrame += scrollBarFadeDuration;
10349 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
10350
10351 state = FADING;
10352
10353 // Kick off the fade animation
10354 host.invalidate();
10355 }
10356 }
10357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010358 }
10359}