AdapterViewAnimator.java revision 69d66e00136f67332c992326a7b2eb334eeb32a2
1/* 2 * Copyright (C) 2010 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.widget; 18 19import java.util.ArrayList; 20import java.util.HashMap; 21 22import android.animation.AnimatorInflater; 23import android.animation.ObjectAnimator; 24import android.content.Context; 25import android.content.Intent; 26import android.content.res.TypedArray; 27import android.os.Handler; 28import android.os.Looper; 29import android.os.Parcel; 30import android.os.Parcelable; 31import android.util.AttributeSet; 32import android.view.MotionEvent; 33import android.view.View; 34import android.view.ViewConfiguration; 35import android.view.ViewGroup; 36 37/** 38 * Base class for a {@link AdapterView} that will perform animations 39 * when switching between its views. 40 * 41 * @attr ref android.R.styleable#AdapterViewAnimator_inAnimation 42 * @attr ref android.R.styleable#AdapterViewAnimator_outAnimation 43 * @attr ref android.R.styleable#AdapterViewAnimator_animateFirstView 44 * @attr ref android.R.styleable#AdapterViewAnimator_loopViews 45 */ 46public abstract class AdapterViewAnimator extends AdapterView<Adapter> 47 implements RemoteViewsAdapter.RemoteAdapterConnectionCallback, Advanceable { 48 private static final String TAG = "RemoteViewAnimator"; 49 50 /** 51 * The index of the current child, which appears anywhere from the beginning 52 * to the end of the current set of children, as specified by {@link #mActiveOffset} 53 */ 54 int mWhichChild = 0; 55 56 /** 57 * Whether or not the first view(s) should be animated in 58 */ 59 boolean mAnimateFirstTime = true; 60 61 /** 62 * Represents where the in the current window of 63 * views the current <code>mDisplayedChild</code> sits 64 */ 65 int mActiveOffset = 0; 66 67 /** 68 * The number of views that the {@link AdapterViewAnimator} keeps as children at any 69 * given time (not counting views that are pending removal, see {@link #mPreviousViews}). 70 */ 71 int mMaxNumActiveViews = 1; 72 73 /** 74 * Map of the children of the {@link AdapterViewAnimator}. 75 */ 76 HashMap<Integer, ViewAndIndex> mViewsMap = new HashMap<Integer, ViewAndIndex>(); 77 78 /** 79 * List of views pending removal from the {@link AdapterViewAnimator} 80 */ 81 ArrayList<Integer> mPreviousViews; 82 83 /** 84 * The index, relative to the adapter, of the beginning of the window of views 85 */ 86 int mCurrentWindowStart = 0; 87 88 /** 89 * The index, relative to the adapter, of the end of the window of views 90 */ 91 int mCurrentWindowEnd = -1; 92 93 /** 94 * The same as {@link #mCurrentWindowStart}, except when the we have bounded 95 * {@link #mCurrentWindowStart} to be non-negative 96 */ 97 int mCurrentWindowStartUnbounded = 0; 98 99 /** 100 * Handler to post events to the main thread 101 */ 102 Handler mMainQueue; 103 104 /** 105 * Listens for data changes from the adapter 106 */ 107 AdapterDataSetObserver mDataSetObserver; 108 109 /** 110 * The {@link Adapter} for this {@link AdapterViewAnimator} 111 */ 112 Adapter mAdapter; 113 114 /** 115 * The {@link RemoteViewsAdapter} for this {@link AdapterViewAnimator} 116 */ 117 RemoteViewsAdapter mRemoteViewsAdapter; 118 119 /** 120 * Specifies whether this is the first time the animator is showing views 121 */ 122 boolean mFirstTime = true; 123 124 /** 125 * Specifies if the animator should wrap from 0 to the end and vice versa 126 * or have hard boundaries at the beginning and end 127 */ 128 boolean mLoopViews = true; 129 130 /** 131 * The width and height of some child, used as a size reference in-case our 132 * dimensions are unspecified by the parent. 133 */ 134 int mReferenceChildWidth = -1; 135 int mReferenceChildHeight = -1; 136 137 /** 138 * In and out animations. 139 */ 140 ObjectAnimator mInAnimation; 141 ObjectAnimator mOutAnimation; 142 143 /** 144 * Current touch state. 145 */ 146 private int mTouchMode = TOUCH_MODE_NONE; 147 148 /** 149 * Private touch states. 150 */ 151 static final int TOUCH_MODE_NONE = 0; 152 static final int TOUCH_MODE_DOWN_IN_CURRENT_VIEW = 1; 153 static final int TOUCH_MODE_HANDLED = 2; 154 155 private Runnable mPendingCheckForTap; 156 157 private static final int DEFAULT_ANIMATION_DURATION = 200; 158 159 public AdapterViewAnimator(Context context) { 160 super(context); 161 initViewAnimator(); 162 } 163 164 public AdapterViewAnimator(Context context, AttributeSet attrs) { 165 super(context, attrs); 166 167 TypedArray a = context.obtainStyledAttributes(attrs, 168 com.android.internal.R.styleable.AdapterViewAnimator); 169 int resource = a.getResourceId( 170 com.android.internal.R.styleable.AdapterViewAnimator_inAnimation, 0); 171 if (resource > 0) { 172 setInAnimation(context, resource); 173 } else { 174 setInAnimation(getDefaultInAnimation()); 175 } 176 177 resource = a.getResourceId(com.android.internal.R.styleable.AdapterViewAnimator_outAnimation, 0); 178 if (resource > 0) { 179 setOutAnimation(context, resource); 180 } else { 181 setOutAnimation(getDefaultOutAnimation()); 182 } 183 184 boolean flag = a.getBoolean( 185 com.android.internal.R.styleable.AdapterViewAnimator_animateFirstView, true); 186 setAnimateFirstView(flag); 187 188 mLoopViews = a.getBoolean( 189 com.android.internal.R.styleable.AdapterViewAnimator_loopViews, false); 190 191 a.recycle(); 192 193 initViewAnimator(); 194 } 195 196 /** 197 * Initialize this {@link AdapterViewAnimator} 198 */ 199 private void initViewAnimator() { 200 mMainQueue = new Handler(Looper.myLooper()); 201 mPreviousViews = new ArrayList<Integer>(); 202 } 203 204 class ViewAndIndex { 205 ViewAndIndex(View v, int i) { 206 view = v; 207 index = i; 208 } 209 View view; 210 int index; 211 } 212 213 /** 214 * This method is used by subclasses to configure the animator to display the 215 * desired number of views, and specify the offset 216 * 217 * @param numVisibleViews The number of views the animator keeps in the {@link ViewGroup} 218 * @param activeOffset This parameter specifies where the current index ({@link #mWhichChild}) 219 * sits within the window. For example if activeOffset is 1, and numVisibleViews is 3, 220 * and {@link #setDisplayedChild(int)} is called with 10, then the effective window will 221 * be the indexes 9, 10, and 11. In the same example, if activeOffset were 0, then the 222 * window would instead contain indexes 10, 11 and 12. 223 * @param shouldLoop If the animator is show view 0, and setPrevious() is called, do we 224 * we loop back to the end, or do we do nothing 225 */ 226 void configureViewAnimator(int numVisibleViews, int activeOffset) { 227 if (activeOffset > numVisibleViews - 1) { 228 // Throw an exception here. 229 } 230 mMaxNumActiveViews = numVisibleViews; 231 mActiveOffset = activeOffset; 232 mPreviousViews.clear(); 233 mViewsMap.clear(); 234 removeAllViewsInLayout(); 235 mCurrentWindowStart = 0; 236 mCurrentWindowEnd = -1; 237 } 238 239 /** 240 * This class should be overridden by subclasses to customize view transitions within 241 * the set of visible views 242 * 243 * @param fromIndex The relative index within the window that the view was in, -1 if it wasn't 244 * in the window 245 * @param toIndex The relative index within the window that the view is going to, -1 if it is 246 * being removed 247 * @param view The view that is being animated 248 */ 249 void animateViewForTransition(int fromIndex, int toIndex, View view) { 250 if (fromIndex == -1) { 251 mInAnimation.setTarget(view); 252 mInAnimation.start(); 253 } else if (toIndex == -1) { 254 mOutAnimation.setTarget(view); 255 mOutAnimation.start(); 256 } 257 } 258 259 ObjectAnimator getDefaultInAnimation() { 260 ObjectAnimator anim = ObjectAnimator.ofFloat(null, "alpha", 0.0f, 1.0f); 261 anim.setDuration(DEFAULT_ANIMATION_DURATION); 262 return anim; 263 } 264 265 ObjectAnimator getDefaultOutAnimation() { 266 ObjectAnimator anim = ObjectAnimator.ofFloat(null, "alpha", 1.0f, 0.0f); 267 anim.setDuration(DEFAULT_ANIMATION_DURATION); 268 return anim; 269 } 270 271 /** 272 * Sets which child view will be displayed. 273 * 274 * @param whichChild the index of the child view to display 275 */ 276 public void setDisplayedChild(int whichChild) { 277 if (mAdapter != null) { 278 mWhichChild = whichChild; 279 if (whichChild >= getWindowSize()) { 280 mWhichChild = mLoopViews ? 0 : getWindowSize() - 1; 281 } else if (whichChild < 0) { 282 mWhichChild = mLoopViews ? getWindowSize() - 1 : 0; 283 } 284 285 boolean hasFocus = getFocusedChild() != null; 286 // This will clear old focus if we had it 287 showOnly(mWhichChild); 288 if (hasFocus) { 289 // Try to retake focus if we had it 290 requestFocus(FOCUS_FORWARD); 291 } 292 } 293 } 294 295 /** 296 * To be overridden by subclasses. This method applies a view / index specific 297 * transform to the child view. 298 * 299 * @param child 300 * @param relativeIndex 301 */ 302 void applyTransformForChildAtIndex(View child, int relativeIndex) { 303 } 304 305 /** 306 * Returns the index of the currently displayed child view. 307 */ 308 public int getDisplayedChild() { 309 return mWhichChild; 310 } 311 312 /** 313 * Manually shows the next child. 314 */ 315 public void showNext() { 316 setDisplayedChild(mWhichChild + 1); 317 } 318 319 /** 320 * Manually shows the previous child. 321 */ 322 public void showPrevious() { 323 setDisplayedChild(mWhichChild - 1); 324 } 325 326 /** 327 * Shows only the specified child. The other displays Views exit the screen, 328 * optionally with the with the {@link #getOutAnimation() out animation} and 329 * the specified child enters the screen, optionally with the 330 * {@link #getInAnimation() in animation}. 331 * 332 * @param childIndex The index of the child to be shown. 333 * @param animate Whether or not to use the in and out animations, defaults 334 * to true. 335 */ 336 void showOnly(int childIndex, boolean animate) { 337 showOnly(childIndex, animate, false); 338 } 339 340 int modulo(int pos, int size) { 341 if (size > 0) { 342 return (size + (pos % size)) % size; 343 } else { 344 return 0; 345 } 346 } 347 348 /** 349 * Get the view at this index relative to the current window's start 350 * 351 * @param relativeIndex Position relative to the current window's start 352 * @return View at this index, null if the index is outside the bounds 353 */ 354 View getViewAtRelativeIndex(int relativeIndex) { 355 if (relativeIndex >= 0 && relativeIndex <= getNumActiveViews() - 1 && mAdapter != null) { 356 int i = modulo(mCurrentWindowStartUnbounded + relativeIndex, getWindowSize()); 357 if (mViewsMap.get(i) != null) { 358 return mViewsMap.get(i).view; 359 } 360 } 361 return null; 362 } 363 364 int getNumActiveViews() { 365 if (mAdapter != null) { 366 return Math.min(mAdapter.getCount() + 1, mMaxNumActiveViews); 367 } else { 368 return mMaxNumActiveViews; 369 } 370 } 371 372 int getWindowSize() { 373 if (mAdapter != null) { 374 int adapterCount = mAdapter.getCount(); 375 if (adapterCount <= getNumActiveViews() && mLoopViews) { 376 return adapterCount*mMaxNumActiveViews; 377 } else { 378 return adapterCount; 379 } 380 } else { 381 return 0; 382 } 383 } 384 385 LayoutParams createOrReuseLayoutParams(View v) { 386 final ViewGroup.LayoutParams currentLp = v.getLayoutParams(); 387 if (currentLp instanceof ViewGroup.LayoutParams) { 388 LayoutParams lp = (LayoutParams) currentLp; 389 return lp; 390 } 391 return new ViewGroup.LayoutParams(0, 0); 392 } 393 394 void refreshChildren() { 395 if (mAdapter == null) return; 396 for (int i = mCurrentWindowStart; i <= mCurrentWindowEnd; i++) { 397 int index = modulo(i, getWindowSize()); 398 399 int adapterCount = mAdapter.getCount(); 400 // get the fresh child from the adapter 401 View updatedChild = mAdapter.getView(modulo(i, adapterCount), null, this); 402 403 if (mViewsMap.containsKey(index)) { 404 FrameLayout fl = (FrameLayout) mViewsMap.get(index).view; 405 // flush out the old child 406 fl.removeAllViewsInLayout(); 407 // add the new child to the frame, if it exists 408 if (updatedChild != null) { 409 fl.addView(updatedChild); 410 } 411 } 412 } 413 } 414 415 /** 416 * This method can be overridden so that subclasses can provide a custom frame in which their 417 * children can live. For example, StackView adds padding to its childrens' frames so as to 418 * accomodate for the highlight effect. 419 * 420 * @return The FrameLayout into which children can be placed. 421 */ 422 FrameLayout getFrameForChild() { 423 return new FrameLayout(mContext); 424 } 425 426 void showOnly(int childIndex, boolean animate, boolean onLayout) { 427 if (mAdapter == null) return; 428 final int adapterCount = mAdapter.getCount(); 429 if (adapterCount == 0) return; 430 431 for (int i = 0; i < mPreviousViews.size(); i++) { 432 View viewToRemove = mViewsMap.get(mPreviousViews.get(i)).view; 433 mViewsMap.remove(mPreviousViews.get(i)); 434 viewToRemove.clearAnimation(); 435 if (viewToRemove instanceof ViewGroup) { 436 ViewGroup vg = (ViewGroup) viewToRemove; 437 vg.removeAllViewsInLayout(); 438 } 439 // applyTransformForChildAtIndex here just allows for any cleanup 440 // associated with this view that may need to be done by a subclass 441 applyTransformForChildAtIndex(viewToRemove, -1); 442 443 removeViewInLayout(viewToRemove); 444 } 445 mPreviousViews.clear(); 446 int newWindowStartUnbounded = childIndex - mActiveOffset; 447 int newWindowEndUnbounded = newWindowStartUnbounded + getNumActiveViews() - 1; 448 int newWindowStart = Math.max(0, newWindowStartUnbounded); 449 int newWindowEnd = Math.min(adapterCount - 1, newWindowEndUnbounded); 450 451 if (mLoopViews) { 452 newWindowStart = newWindowStartUnbounded; 453 newWindowEnd = newWindowEndUnbounded; 454 } 455 int rangeStart = modulo(newWindowStart, getWindowSize()); 456 int rangeEnd = modulo(newWindowEnd, getWindowSize()); 457 458 boolean wrap = false; 459 if (rangeStart > rangeEnd) { 460 wrap = true; 461 } 462 463 // This section clears out any items that are in our active views list 464 // but are outside the effective bounds of our window (this is becomes an issue 465 // at the extremities of the list, eg. where newWindowStartUnbounded < 0 or 466 // newWindowEndUnbounded > mAdapter.getCount() - 1 467 for (Integer index : mViewsMap.keySet()) { 468 boolean remove = false; 469 if (!wrap && (index < rangeStart || index > rangeEnd)) { 470 remove = true; 471 } else if (wrap && (index > rangeEnd && index < rangeStart)) { 472 remove = true; 473 } 474 475 if (remove) { 476 View previousView = mViewsMap.get(index).view; 477 int oldRelativeIndex = mViewsMap.get(index).index; 478 479 mPreviousViews.add(index); 480 animateViewForTransition(oldRelativeIndex, -1, previousView); 481 } 482 } 483 484 // If the window has changed 485 if (!(newWindowStart == mCurrentWindowStart && newWindowEnd == mCurrentWindowEnd && 486 newWindowStartUnbounded == mCurrentWindowStartUnbounded)) { 487 // Run through the indices in the new range 488 for (int i = newWindowStart; i <= newWindowEnd; i++) { 489 490 int index = modulo(i, getWindowSize()); 491 int oldRelativeIndex; 492 if (mViewsMap.containsKey(index)) { 493 oldRelativeIndex = mViewsMap.get(index).index; 494 } else { 495 oldRelativeIndex = -1; 496 } 497 int newRelativeIndex = i - newWindowStartUnbounded; 498 499 // If this item is in the current window, great, we just need to apply 500 // the transform for it's new relative position in the window, and animate 501 // between it's current and new relative positions 502 boolean inOldRange = mViewsMap.containsKey(index) && !mPreviousViews.contains(index); 503 504 if (inOldRange) { 505 View view = mViewsMap.get(index).view; 506 mViewsMap.get(index).index = newRelativeIndex; 507 applyTransformForChildAtIndex(view, newRelativeIndex); 508 animateViewForTransition(oldRelativeIndex, newRelativeIndex, view); 509 510 // Otherwise this view is new to the window 511 } else { 512 // Get the new view from the adapter, add it and apply any transform / animation 513 View newView = mAdapter.getView(modulo(i, adapterCount), null, this); 514 515 // We wrap the new view in a FrameLayout so as to respect the contract 516 // with the adapter, that is, that we don't modify this view directly 517 FrameLayout fl = getFrameForChild(); 518 519 // If the view from the adapter is null, we still keep an empty frame in place 520 if (newView != null) { 521 fl.addView(newView); 522 } 523 mViewsMap.put(index, new ViewAndIndex(fl, newRelativeIndex)); 524 addChild(fl); 525 applyTransformForChildAtIndex(fl, newRelativeIndex); 526 animateViewForTransition(-1, newRelativeIndex, fl); 527 } 528 mViewsMap.get(index).view.bringToFront(); 529 } 530 mCurrentWindowStart = newWindowStart; 531 mCurrentWindowEnd = newWindowEnd; 532 mCurrentWindowStartUnbounded = newWindowStartUnbounded; 533 } 534 535 mFirstTime = false; 536 if (!onLayout) { 537 requestLayout(); 538 invalidate(); 539 } else { 540 // If the Adapter tries to layout the current view when we get it using getView 541 // above the layout will end up being ignored since we are currently laying out, so 542 // we post a delayed requestLayout and invalidate 543 mMainQueue.post(new Runnable() { 544 public void run() { 545 requestLayout(); 546 invalidate(); 547 } 548 }); 549 } 550 } 551 552 private void addChild(View child) { 553 addViewInLayout(child, -1, createOrReuseLayoutParams(child)); 554 555 // This code is used to obtain a reference width and height of a child in case we need 556 // to decide our own size. TODO: Do we want to update the size of the child that we're 557 // using for reference size? If so, when? 558 if (mReferenceChildWidth == -1 || mReferenceChildHeight == -1) { 559 int measureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); 560 child.measure(measureSpec, measureSpec); 561 mReferenceChildWidth = child.getMeasuredWidth(); 562 mReferenceChildHeight = child.getMeasuredHeight(); 563 } 564 } 565 566 void showTapFeedback(View v) { 567 v.setPressed(true); 568 } 569 570 void hideTapFeedback(View v) { 571 v.setPressed(false); 572 } 573 574 void cancelHandleClick() { 575 View v = getCurrentView(); 576 if (v != null) { 577 hideTapFeedback(v); 578 } 579 mTouchMode = TOUCH_MODE_NONE; 580 } 581 582 final class CheckForTap implements Runnable { 583 public void run() { 584 if (mTouchMode == TOUCH_MODE_DOWN_IN_CURRENT_VIEW) { 585 View v = getCurrentView(); 586 showTapFeedback(v); 587 } 588 } 589 } 590 591 @Override 592 public boolean onTouchEvent(MotionEvent ev) { 593 int action = ev.getAction(); 594 boolean handled = false; 595 switch (action) { 596 case MotionEvent.ACTION_DOWN: { 597 View v = getCurrentView(); 598 if (v != null) { 599 if (isTransformedTouchPointInView(ev.getX(), ev.getY(), v, null)) { 600 if (mPendingCheckForTap == null) { 601 mPendingCheckForTap = new CheckForTap(); 602 } 603 mTouchMode = TOUCH_MODE_DOWN_IN_CURRENT_VIEW; 604 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 605 } 606 } 607 break; 608 } 609 case MotionEvent.ACTION_MOVE: break; 610 case MotionEvent.ACTION_POINTER_UP: break; 611 case MotionEvent.ACTION_UP: { 612 if (mTouchMode == TOUCH_MODE_DOWN_IN_CURRENT_VIEW) { 613 final View v = getCurrentView(); 614 if (v != null) { 615 if (isTransformedTouchPointInView(ev.getX(), ev.getY(), v, null)) { 616 final Handler handler = getHandler(); 617 if (handler != null) { 618 handler.removeCallbacks(mPendingCheckForTap); 619 } 620 showTapFeedback(v); 621 postDelayed(new Runnable() { 622 public void run() { 623 hideTapFeedback(v); 624 post(new Runnable() { 625 public void run() { 626 performItemClick(v, 0, 0); 627 } 628 }); 629 } 630 }, ViewConfiguration.getPressedStateDuration()); 631 handled = true; 632 } 633 } 634 } 635 mTouchMode = TOUCH_MODE_NONE; 636 break; 637 } 638 case MotionEvent.ACTION_CANCEL: { 639 View v = getCurrentView(); 640 if (v != null) { 641 hideTapFeedback(v); 642 } 643 mTouchMode = TOUCH_MODE_NONE; 644 } 645 } 646 return handled; 647 } 648 649 private void measureChildren() { 650 final int count = getChildCount(); 651 final int childWidth = getMeasuredWidth() - mPaddingLeft - mPaddingRight; 652 final int childHeight = getMeasuredHeight() - mPaddingTop - mPaddingBottom; 653 654 for (int i = 0; i < count; i++) { 655 final View child = getChildAt(i); 656 child.measure(MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY), 657 MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY)); 658 } 659 } 660 661 @Override 662 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 663 int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); 664 int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); 665 final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); 666 final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); 667 668 boolean haveChildRefSize = (mReferenceChildWidth != -1 && mReferenceChildHeight != -1); 669 670 // We need to deal with the case where our parent hasn't told us how 671 // big we should be. In this case we try to use the desired size of the first 672 // child added. 673 if (heightSpecMode == MeasureSpec.UNSPECIFIED) { 674 heightSpecSize = haveChildRefSize ? mReferenceChildHeight + mPaddingTop + 675 mPaddingBottom : 0; 676 } else if (heightSpecMode == MeasureSpec.AT_MOST) { 677 if (haveChildRefSize) { 678 int height = mReferenceChildHeight + mPaddingTop + mPaddingBottom; 679 if (height > heightSpecSize) { 680 heightSpecSize |= MEASURED_STATE_TOO_SMALL; 681 } else { 682 heightSpecSize = height; 683 } 684 } 685 } 686 687 if (widthSpecMode == MeasureSpec.UNSPECIFIED) { 688 widthSpecSize = haveChildRefSize ? mReferenceChildWidth + mPaddingLeft + 689 mPaddingRight : 0; 690 } else if (heightSpecMode == MeasureSpec.AT_MOST) { 691 if (haveChildRefSize) { 692 int width = mReferenceChildWidth + mPaddingLeft + mPaddingRight; 693 if (width > widthSpecSize) { 694 widthSpecSize |= MEASURED_STATE_TOO_SMALL; 695 } else { 696 widthSpecSize = width; 697 } 698 } 699 } 700 701 setMeasuredDimension(widthSpecSize, heightSpecSize); 702 measureChildren(); 703 } 704 705 @Override 706 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 707 boolean dataChanged = mDataChanged; 708 if (dataChanged) { 709 handleDataChanged(); 710 711 // if the data changes, mWhichChild might be out of the bounds of the adapter 712 // in this case, we reset mWhichChild to the beginning 713 if (mWhichChild >= mAdapter.getCount()) { 714 mWhichChild = 0; 715 716 showOnly(mWhichChild, true, true); 717 } 718 refreshChildren(); 719 } 720 721 final int childCount = getChildCount(); 722 for (int i = 0; i < childCount; i++) { 723 final View child = getChildAt(i); 724 725 int childRight = mPaddingLeft + child.getMeasuredWidth(); 726 int childBottom = mPaddingTop + child.getMeasuredHeight(); 727 728 child.layout(mPaddingLeft, mPaddingTop, childRight, childBottom); 729 } 730 mDataChanged = false; 731 } 732 733 static class SavedState extends BaseSavedState { 734 int whichChild; 735 736 /** 737 * Constructor called from {@link AdapterViewAnimator#onSaveInstanceState()} 738 */ 739 SavedState(Parcelable superState, int whichChild) { 740 super(superState); 741 this.whichChild = whichChild; 742 } 743 744 /** 745 * Constructor called from {@link #CREATOR} 746 */ 747 private SavedState(Parcel in) { 748 super(in); 749 this.whichChild = in.readInt(); 750 } 751 752 @Override 753 public void writeToParcel(Parcel out, int flags) { 754 super.writeToParcel(out, flags); 755 out.writeInt(this.whichChild); 756 } 757 758 @Override 759 public String toString() { 760 return "AdapterViewAnimator.SavedState{ whichChild = " + this.whichChild + " }"; 761 } 762 763 public static final Parcelable.Creator<SavedState> CREATOR 764 = new Parcelable.Creator<SavedState>() { 765 public SavedState createFromParcel(Parcel in) { 766 return new SavedState(in); 767 } 768 769 public SavedState[] newArray(int size) { 770 return new SavedState[size]; 771 } 772 }; 773 } 774 775 @Override 776 public Parcelable onSaveInstanceState() { 777 Parcelable superState = super.onSaveInstanceState(); 778 return new SavedState(superState, mWhichChild); 779 } 780 781 @Override 782 public void onRestoreInstanceState(Parcelable state) { 783 SavedState ss = (SavedState) state; 784 super.onRestoreInstanceState(ss.getSuperState()); 785 786 // Here we set mWhichChild in addition to setDisplayedChild 787 // We do the former in case mAdapter is null, and hence setDisplayedChild won't 788 // set mWhichChild 789 mWhichChild = ss.whichChild; 790 791 setDisplayedChild(mWhichChild); 792 } 793 794 /** 795 * Shows only the specified child. The other displays Views exit the screen 796 * with the {@link #getOutAnimation() out animation} and the specified child 797 * enters the screen with the {@link #getInAnimation() in animation}. 798 * 799 * @param childIndex The index of the child to be shown. 800 */ 801 void showOnly(int childIndex) { 802 final boolean animate = (!mFirstTime || mAnimateFirstTime); 803 showOnly(childIndex, animate); 804 } 805 806 /** 807 * Returns the View corresponding to the currently displayed child. 808 * 809 * @return The View currently displayed. 810 * 811 * @see #getDisplayedChild() 812 */ 813 public View getCurrentView() { 814 return getViewAtRelativeIndex(mActiveOffset); 815 } 816 817 /** 818 * Returns the current animation used to animate a View that enters the screen. 819 * 820 * @return An Animation or null if none is set. 821 * 822 * @see #setInAnimation(android.animation.ObjectAnimator) 823 * @see #setInAnimation(android.content.Context, int) 824 */ 825 public ObjectAnimator getInAnimation() { 826 return mInAnimation; 827 } 828 829 /** 830 * Specifies the animation used to animate a View that enters the screen. 831 * 832 * @param inAnimation The animation started when a View enters the screen. 833 * 834 * @see #getInAnimation() 835 * @see #setInAnimation(android.content.Context, int) 836 */ 837 public void setInAnimation(ObjectAnimator inAnimation) { 838 mInAnimation = inAnimation; 839 } 840 841 /** 842 * Returns the current animation used to animate a View that exits the screen. 843 * 844 * @return An Animation or null if none is set. 845 * 846 * @see #setOutAnimation(android.animation.ObjectAnimator) 847 * @see #setOutAnimation(android.content.Context, int) 848 */ 849 public ObjectAnimator getOutAnimation() { 850 return mOutAnimation; 851 } 852 853 /** 854 * Specifies the animation used to animate a View that exit the screen. 855 * 856 * @param outAnimation The animation started when a View exit the screen. 857 * 858 * @see #getOutAnimation() 859 * @see #setOutAnimation(android.content.Context, int) 860 */ 861 public void setOutAnimation(ObjectAnimator outAnimation) { 862 mOutAnimation = outAnimation; 863 } 864 865 /** 866 * Specifies the animation used to animate a View that enters the screen. 867 * 868 * @param context The application's environment. 869 * @param resourceID The resource id of the animation. 870 * 871 * @see #getInAnimation() 872 * @see #setInAnimation(android.animation.ObjectAnimator) 873 */ 874 public void setInAnimation(Context context, int resourceID) { 875 setInAnimation((ObjectAnimator) AnimatorInflater.loadAnimator(context, resourceID)); 876 } 877 878 /** 879 * Specifies the animation used to animate a View that exit the screen. 880 * 881 * @param context The application's environment. 882 * @param resourceID The resource id of the animation. 883 * 884 * @see #getOutAnimation() 885 * @see #setOutAnimation(android.animation.ObjectAnimator) 886 */ 887 public void setOutAnimation(Context context, int resourceID) { 888 setOutAnimation((ObjectAnimator) AnimatorInflater.loadAnimator(context, resourceID)); 889 } 890 891 /** 892 * Indicates whether the current View should be animated the first time 893 * the ViewAnimation is displayed. 894 * 895 * @param animate True to animate the current View the first time it is displayed, 896 * false otherwise. 897 */ 898 public void setAnimateFirstView(boolean animate) { 899 mAnimateFirstTime = animate; 900 } 901 902 @Override 903 public int getBaseline() { 904 return (getCurrentView() != null) ? getCurrentView().getBaseline() : super.getBaseline(); 905 } 906 907 @Override 908 public Adapter getAdapter() { 909 return mAdapter; 910 } 911 912 @Override 913 public void setAdapter(Adapter adapter) { 914 if (mAdapter != null && mDataSetObserver != null) { 915 mAdapter.unregisterDataSetObserver(mDataSetObserver); 916 } 917 918 mAdapter = adapter; 919 checkFocus(); 920 921 if (mAdapter != null) { 922 mDataSetObserver = new AdapterDataSetObserver(); 923 mAdapter.registerDataSetObserver(mDataSetObserver); 924 } 925 setFocusable(true); 926 } 927 928 /** 929 * Sets up this AdapterViewAnimator to use a remote views adapter which connects to a 930 * RemoteViewsService through the specified intent. 931 * 932 * @param intent the intent used to identify the RemoteViewsService for the adapter to 933 * connect to. 934 */ 935 @android.view.RemotableViewMethod 936 public void setRemoteViewsAdapter(Intent intent) { 937 // Ensure that we don't already have a RemoteViewsAdapter that is bound to an existing 938 // service handling the specified intent. 939 if (mRemoteViewsAdapter != null) { 940 Intent.FilterComparison fcNew = new Intent.FilterComparison(intent); 941 Intent.FilterComparison fcOld = new Intent.FilterComparison( 942 mRemoteViewsAdapter.getRemoteViewsServiceIntent()); 943 if (fcNew.equals(fcOld)) { 944 return; 945 } 946 } 947 948 // Otherwise, create a new RemoteViewsAdapter for binding 949 mRemoteViewsAdapter = new RemoteViewsAdapter(getContext(), intent, this); 950 } 951 952 @Override 953 public void setSelection(int position) { 954 setDisplayedChild(position); 955 } 956 957 @Override 958 public View getSelectedView() { 959 return getViewAtRelativeIndex(mActiveOffset); 960 } 961 962 /** 963 * Called back when the adapter connects to the RemoteViewsService. 964 */ 965 public void onRemoteAdapterConnected() { 966 if (mRemoteViewsAdapter != mAdapter) { 967 setAdapter(mRemoteViewsAdapter); 968 } else if (mRemoteViewsAdapter != null) { 969 mRemoteViewsAdapter.superNotifyDataSetChanged(); 970 } 971 } 972 973 /** 974 * Called back when the adapter disconnects from the RemoteViewsService. 975 */ 976 public void onRemoteAdapterDisconnected() { 977 // If the remote adapter disconnects, we keep it around 978 // since the currently displayed items are still cached. 979 // Further, we want the service to eventually reconnect 980 // when necessary, as triggered by this view requesting 981 // items from the Adapter. 982 } 983 984 public void advance() { 985 showNext(); 986 } 987 988 public void willBeAdvancedByHost() { 989 } 990 991 @Override 992 protected void onDetachedFromWindow() { 993 mAdapter = null; 994 super.onDetachedFromWindow(); 995 } 996} 997