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

ViewPager 自定義標題欄實戰:用 TranslateAnimation 實現下划线滑動

編輯:關於 Android 程式設計

上一篇用 Google 提供的 PagerTabStrip 與 PagerTitleStrip 給 ViewPager 加了標題,但實際項目中這兩個控件的樣式往往不夠用,絕大多數產品仍選擇自定義標題欄。本文就來實現一個帶滑動指示器的版本。

一、總體布局

選擇 RelativeLayout,需要牢記它的佈局規則是「先來後到」:重疊時後定義的控件會蓋在先定義的上面。因此先放一個充滿父容器的 ViewPager,再在頂部疊一個線性布局用來擺放各頁標題,線性布局下方放一個 ImageView 作為滑動指示器。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager_define_title"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:id="@+id/linear_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:orientation="vertical">

        <!-- 三個 TextView 作為標題,此處省略 -->

        <ImageView
            android:id="@+id/imageview_cursor"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="matrix"
            android:src="@mipmap/image" />
    </LinearLayout>
</RelativeLayout>

二、自定義 PagerAdapter

繼承 PagerAdapter 並實現四個核心方法:getCount、isViewFromObject、instantiateItem、destroyItem。

public class MyPagerAdapter extends PagerAdapter {
    private List<View> mViews;

    public MyPagerAdapter(List<View> mViews) {
        this.mViews = mViews;
    }

    @Override
    public int getCount() {
        return mViews.size(); // 這裡為 3
    }

    @Override
    public boolean isViewFromObject(View view, Object o) {
        return view == o;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        container.addView(mViews.get(position));
        return mViews.get(position);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(mViews.get(position));
    }
}

三、Activity 中的滑動動畫

public class DefineTitleActivity extends Activity {
    private List<View> mViews;
    private LayoutInflater mInflater;
    private ViewPager mViewPager;
    private ImageView mImageCursor;   // 指示器
    private int mCursorWidth;         // 指示器圖片寬度
    private int mOffset;              // 居中所需的偏移量
    private int currIndex = 0;        // 當前頁序號
    private MyPagerAdapter myPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_define_title);

        mViewPager = (ViewPager) findViewById(R.id.viewpager_define_title);
        mInflater = getLayoutInflater();

        mViews = new ArrayList<View>();
        mViews.add(mInflater.inflate(R.layout.item_frist, null));
        mViews.add(mInflater.inflate(R.layout.item_second, null));
        mViews.add(mInflater.inflate(R.layout.item_third, null));

        initCursorPos();

        myPagerAdapter = new MyPagerAdapter(mViews);
        mViewPager.setAdapter(myPagerAdapter);

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            // 頁卡1 → 頁卡2 的偏移量
            int one = mOffset * 2 + mCursorWidth;
            // 頁卡1 → 頁卡3 的偏移量
            int two = one * 2;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }

            @Override
            public void onPageSelected(int position) {
                Animation animation = null;
                switch (position) {
                    case 0:
                        if (currIndex == 1) animation = new TranslateAnimation(one, 0, 0, 0);
                        else if (currIndex == 2) animation = new TranslateAnimation(two, 0, 0, 0);
                        break;
                    case 1:
                        if (currIndex == 0) animation = new TranslateAnimation(mOffset, one, 0, 0);
                        else if (currIndex == 2) animation = new TranslateAnimation(two, one, 0, 0);
                        break;
                    case 2:
                        if (currIndex == 0) animation = new TranslateAnimation(mOffset, two, 0, 0);
                        else if (currIndex == 1) animation = new TranslateAnimation(one, two, 0, 0);
                        break;
                }
                currIndex = position;
                if (animation != null) {
                    animation.setFillAfter(true); // 停留在動畫結束位置
                    animation.setDuration(300);
                    mImageCursor.startAnimation(animation);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) { }
        });
    }

    /** 計算偏移量並設置指示器初始位置 */
    private void initCursorPos() {
        mImageCursor = (ImageView) findViewById(R.id.imageview_cursor);
        mCursorWidth = BitmapFactory.decodeResource(getResources(), R.mipmap.image).getWidth();

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int screenW = metrics.widthPixels;

        // 讓指示器居中於第一個標題下方
        mOffset = (screenW / mViews.size() - mCursorWidth) / 2;

        Matrix matrix = new Matrix();
        matrix.postTranslate(mOffset, 0);
        mImageCursor.setImageMatrix(matrix);
    }
}

這段代碼的難點在於「移動多少」。核心思路是:把屏幕寬度按頁數均分得到每個標題的佔位寬度,減去指示器自身寬度後除以二,就是讓指示器居中所需的 mOffset;相鄰兩頁之間的位移量是 mOffset * 2 + mCursorWidth,跨兩頁則再翻倍。理解這組數字後,onPageSelected 裡那個 switch 就只是在查表:根據「從哪來、到哪去」選出正確的起止坐標。

最終效果:

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