Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android ViewFlipper 實作左右滑動輪播與轉場動畫

編輯:關於 Android 程式設計

要做左右滑動切換畫面,可用的元件不少:ViewPager、Gallery、自行繼承 ViewGroup 都是選項。本文示範用 ViewFlipper 搭配手勢偵測與補間動畫,完成一個可自動播放、也能手動滑動的輪播效果。

會用到的三個關鍵類別

  • ViewFlipper:容器性質的元件,可以放進多個子 View,但同一時間只顯示一個。
  • GestureDetector:負責辨識使用者的滑動手勢。
  • Animation:負責進出畫面的轉場效果。

ViewFlipper 很適合拿來做廣告輪播——開啟自動播放之後,內容就會定時往下捲動。

核心原理:手勢向右滑動時呼叫 showNext(),向左滑動時呼叫 showPrevious(),再各自搭配進場與退場動畫。

第一步:在版面檔加入 ViewFlipper

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/pattern1" >
    <Button android:id="@+id/treasure_chest_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:background="@drawable/treasure" />
    <ViewFlipper android:id="@+id/viewflipper"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/treasure_chest_btn" >
    </ViewFlipper>
    <Button android:id="@+id/garbage_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/viewflipper"
        android:background="@drawable/garbage" />
</RelativeLayout>

第二步:在 res/anim 定義四組動畫

slide_left_in.xml(新畫面由右側滑入)

<set xmlns:android="https://schemas.android.com/apk/res/android" >
    <!-- fromXDelta:起始 X 座標;toXDelta:結束 X 座標;duration:持續時間(毫秒) -->
    <translate android:duration="800" android:fromXDelta="100%p" android:toXDelta="0" />
</set>

slide_left_out.xml(舊畫面向左滑出)

<set xmlns:android="https://schemas.android.com/apk/res/android" >
    <translate android:duration="800" android:fromXDelta="0" android:toXDelta="-100%p" />
</set>

slide_right_in.xml(新畫面由左側滑入)

<set xmlns:android="https://schemas.android.com/apk/res/android" >
    <translate android:duration="800" android:fromXDelta="-100%p" android:toXDelta="0" />
</set>

slide_right_out.xml(舊畫面向右滑出)

<set xmlns:android="https://schemas.android.com/apk/res/android" >
    <translate android:duration="800" android:fromXDelta="0" android:toXDelta="100%p" />
</set>

第三步:Activity 中的手勢與動畫串接

public class MainActivity extends Activity implements OnGestureListener, OnTouchListener {
    private GestureDetector detector;
    private ViewFlipper myViewFlipper;
    private int[] imgs = { R.drawable.img0, R.drawable.img1, R.drawable.img2,
                           R.drawable.img3, R.drawable.img4, R.drawable.img5 };
    private int displayedChildIndex = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        myViewFlipper = (ViewFlipper) findViewById(R.id.viewflipper);
        myViewFlipper.setOnTouchListener(this);
        myViewFlipper.setLongClickable(true);
        // myViewFlipper.setAutoStart(true);  // 開啟自動播放
        detector = new GestureDetector(this);
        addFlipperView();
    }

    /** 動態把子 View 塞進 Flipper */
    private void addFlipperView() {
        for (int i = 0; i < imgs.length; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.myviewflipper, null);
            ((TextView) view.findViewById(R.id.view_title)).setText("頭像");
            ((ImageView) view.findViewById(R.id.view_image)).setBackgroundResource(imgs[i]);
            myViewFlipper.addView(view);
        }
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        displayedChildIndex = myViewFlipper.getDisplayedChild();
        final ImageView iv = (ImageView) myViewFlipper
                .getChildAt(displayedChildIndex).findViewById(R.id.view_image);

        if (e2.getX() - e1.getX() >= 100 && e1.getY() - e2.getY() >= 100) {
            // 往右上滑:播放「收集寶物」動畫
            AnimationSet outAnim = (AnimationSet) AnimationUtils.loadAnimation(this, R.anim.collect_treasure);
            iv.startAnimation(outAnim);
            outAnim.setAnimationListener(new AnimationListener() {
                public void onAnimationStart(Animation animation) { }
                public void onAnimationRepeat(Animation animation) { }
                public void onAnimationEnd(Animation animation) {
                    showNextView();
                    iv.clearAnimation();
                }
            });
        } else if (e1.getX() - e2.getX() >= 100 && e2.getY() - e1.getY() >= 100) {
            // 往右下滑:播放「丟垃圾桶」動畫
            AnimationSet outAnim = (AnimationSet) AnimationUtils.loadAnimation(this, R.anim.throw_garbage);
            iv.startAnimation(outAnim);
            outAnim.setAnimationListener(new AnimationListener() {
                public void onAnimationStart(Animation animation) { }
                public void onAnimationRepeat(Animation animation) { }
                public void onAnimationEnd(Animation animation) {
                    showNextView();
                    iv.clearAnimation();
                }
            });
        } else if (e1.getX() - e2.getX() >= 100) {
            showNextView();
        } else if (e2.getX() - e1.getX() >= 100) {
            showPreviousView();
        }
        return false;
    }

    private void showPreviousView() {
        myViewFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_right_in));
        myViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_right_out));
        myViewFlipper.showPrevious();
    }

    private void showNextView() {
        myViewFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_left_in));
        myViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_left_out));
        myViewFlipper.showNext();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return detector.onTouchEvent(event);
    }

    // onDown / onShowPress / onSingleTapUp / onScroll / onLongPress 依需求實作,此處略
}

要留意的是 setInAnimation() 與 setOutAnimation() 必須在呼叫 showNext/showPrevious 之前設定,否則第一次切換會沒有動畫。另外,若同時啟用自動播放與手勢,記得在使用者手動操作時暫停計時器,避免兩者互相干擾。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved