教你如何實現 Android TextView 文字輪播效果

Android入墳之路發表於2019-04-12

效果圖:

教你如何實現 Android TextView 文字輪播效果

實現思路:

1.ViewAnimator 思路
使用 ViewAnimator 自身特性,對期中的子 view 實現動畫切換

2.自定義 viewGroup 思路
在這個思路下,我們自定義一個容器,繼承 FrameLayout ,根據資料數量自己 new 相應數量的 itemView 出來加入 FrameLayout ,動畫是通過對當前 itemView 做一個出去的佛納甘話,同時對下一個 itemView 做一個進入動畫,使用 handle 實現延遲輪換

3.ViewFlipper 思路
ViewFlipper 思路和 ViewAnimator 一樣,不過 ViewFlipper 使用上更靈活,這裡我們根據資料流量動態往 ViewFlipper 裡新增 itemView

5.自定義 textView 思路

其實這個思路也好理解,我們繼承 textView ,然後在 onDraw 繪製中自己話文字,自己做動畫,動畫的思路是先把上一個文字上移到頂,然後再繪製下一個文字,從下面開始一直移動到中間

ViewAnimator 思路

ViewAnimator 是個 viewGroup ,可以實現動畫切換其中子 view 的效果。在 xml 佈局種,我們把 ViewAnimator 當一個容器,裡面寫輪播的 view,寫多少個 view 就有多少個輪播,然後設定切換的動畫,用 handle 做定時延遲輪播,調 ViewAnimator.onNext 就可以切換到下一個 view

實現思路:

1.先在 layout xml 中宣告佈局層級結構:

 <ViewAnimator
        android:layout_width="match_parent"
        android:layout_height="200dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="歡迎"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="測試"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="本程式"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="!!!!!"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="hello,world"/>
    </ViewAnimator>
複製程式碼

2.程式碼種設定切換動畫

viewAnimator.setOutAnimation(this, R.anim.slide_out_up);
viewAnimator.setInAnimation(this, R.anim.slide_in_down);
複製程式碼

3.handle 延遲迴圈顯示下一個

      public void showNext() {
        viewAnimator.showNext();
    }

    public void showPrevious() {
        viewAnimator.showPrevious();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (autoPlayFlag) {
                showNext();
            }
            handler.sendMessageDelayed(new Message(), TIME_INTERVAL);
        }
    };
複製程式碼

我們在需要的位置傳送 handle 事件就可以了

使用 ViewAnimator 有點和確定同樣明顯

  • 優點:使用簡單,沒有難度

  • 缺點:xml 中固定了 view個數,為了相容不同資料量,我們需要再 ViewAnimator 基礎上 2 次開發

自定義 viewGroup 思路

在這個思路下,我們自定義一個容器,繼承 FrameLayout ,根據資料數量自己 new 相應數量的 itemView 出來加入 FrameLayout ,動畫是通過對當前 itemView 做一個出去的佛納甘話,同時對下一個 itemView 做一個進入動畫,使用 handle 實現延遲輪換

思路如下

1.在設定資料時新增相應數量的 itemView 進去

    public void setNoticeList(List<String> list) {

        // 建立TextView
        for (int i = 0; i < list.size(); i++) {
            TextView textView = createTextView(list.get(i));
            mNoticeList.add(textView);
            addView(textView);
        }
        // 顯示第一條公告
        mCurrentNotice = 0;
        mNoticeList.get(mCurrentNotice).setVisibility(VISIBLE);
        // 啟動輪播
        start();
    }

    private TextView createTextView(String text) {
        if (mLayoutParams == null) {
            mLayoutParams = new LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            mLayoutParams.gravity = Gravity.CENTER_VERTICAL;
        }

        TextView textView = new TextView(getContext());
        textView.setLayoutParams(mLayoutParams);
        textView.setSingleLine();
        textView.setEllipsize(TextUtils.TruncateAt.END);
        textView.setTextColor(mTextColor);
        textView.setVisibility(GONE);
        textView.setText(text);
        // 如果有設定字型大小,如果字型大小為null。
        if (mTextSize > 0) {
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
        }
        return textView;
    }
複製程式碼

2.在 handle 裡面啟動 itemView 切換的動畫

     class NoticeRunnable implements Runnable {
        @Override
        public void run() {
            // 隱藏當前的textView
            TextView currentView = mNoticeList.get(mCurrentNotice);
            currentView.setVisibility(GONE);
            if(mExitAnimSet != null) {
                currentView.startAnimation(mExitAnimSet);
            }
            mCurrentNotice++;
            if(mCurrentNotice >= mNoticeList.size()) {
                mCurrentNotice = 0;
            }

            // 顯示下一個TextView
            TextView nextView = mNoticeList.get(mCurrentNotice);
            nextView.setVisibility(VISIBLE);
            if(mEnterAnimSet != null) {
                nextView.startAnimation(mEnterAnimSet);
            }
            mHandler.postDelayed(this, mNoticeDuration);
        }
    }

    private void createEnterAnimation() {
        mEnterAnimSet = new AnimationSet(false);
        TranslateAnimation translateAnimation =
                new TranslateAnimation(0,0,0,0, TranslateAnimation.RELATIVE_TO_PARENT, 1f,
                        TranslateAnimation.RELATIVE_TO_SELF, 0f);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0f,1f);
        mEnterAnimSet.addAnimation(translateAnimation);
        mEnterAnimSet.addAnimation(alphaAnimation);
        mEnterAnimSet.setDuration(DEFAULT_ANIMATION_DURATION);
    }

    private void createExitAnimation() {
        mExitAnimSet = new AnimationSet(false);
        TranslateAnimation translateAnimation =
                new TranslateAnimation(0,0,0,0, TranslateAnimation.RELATIVE_TO_SELF, 0f,
                        TranslateAnimation.RELATIVE_TO_PARENT, -1f);
        AlphaAnimation alphaAnimation = new AlphaAnimation(1f,0f);
        mExitAnimSet.addAnimation(translateAnimation);
        mExitAnimSet.addAnimation(alphaAnimation);
        mExitAnimSet.setDuration(DEFAULT_ANIMATION_DURATION);
    }
複製程式碼

這樣寫最練手,但是我是不推薦這樣乾的,基礎差一些的容易出問題,而且 google 給我們提供了一些實現,我們何必非的自己實現呢,反正這樣寫會花點時間

ViewFlipper 思路

ViewFlipper 思路像是上面 1 和 2 的結合,ViewFlipper 對動畫的控制更優秀一些,我們往 ViewFlipper 裡面動態新增 itemView ,基本都是這個思路,區別是使用的容器不同

這裡推薦一個成熟的庫:

  • TextBannerView

這個庫非常完善了,也能滿足大家的常用需求,是可以拿來直接用的,大家看圖就明白了

教你如何實現 Android TextView 文字輪播效果

思路如下

他這裡自定義了一個 ViewGroup 繼承自 RelativeLayout,在 view 初始化時新增了一個 ViewFlipper 進來,之後操作的都是這個 ViewFlipper 了

1.自定義 ViewGroup 初始化時新增了 ViewFlipper

    /**初始化控制元件*/
    private void init(Context context, AttributeSet attrs, int defStyleAttr) {

        mViewFlipper = new ViewFlipper(getContext());//new 一個ViewAnimator
        mViewFlipper.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        addView(mViewFlipper);
        startViewAnimator();
        //設定點選事件
        mViewFlipper.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = mViewFlipper.getDisplayedChild();//當前顯示的子檢視的索引位置
                if (mListener!=null){
                    mListener.onItemClick(mDatas.get(position),position);
                }
            }
        });
複製程式碼

2.根據資料新增 itemView

      /**設定資料集合*/
    public void setDatas(List<String> datas){
        this.mDatas = datas;
        if (DisplayUtils.notEmpty(mDatas)){
            mViewFlipper.removeAllViews();
            for (int i = 0; i < mDatas.size(); i++) {
                TextView textView = new TextView(getContext());
                textView.setText(mDatas.get(i));
                //任意設定你的文字樣式,在這裡
                textView.setSingleLine(isSingleLine);
                textView.setTextColor(mTextColor);
                textView.setTextSize(mTextSize);
                textView.setGravity(mGravity);

                mViewFlipper.addView(textView,i);//新增子view,並標識子view位置
            }
        }
    }
複製程式碼

3.新增動畫

    /**
     * 設定進入動畫和離開動畫
     *
     * @param inAnimResId  進入動畫的resID
     * @param outAnimResID 離開動畫的resID
     */
    private void setInAndOutAnimation(@AnimRes int inAnimResId, @AnimRes int outAnimResID) {
        Animation inAnim = AnimationUtils.loadAnimation(getContext(), inAnimResId);
        inAnim.setDuration(animDuration);
        mViewFlipper.setInAnimation(inAnim);

        Animation outAnim = AnimationUtils.loadAnimation(getContext(), outAnimResID);
        outAnim.setDuration(animDuration);
        mViewFlipper.setOutAnimation(outAnim);
    }
複製程式碼

之後就是用 handle 來做延遲迴圈,上面複製好幾遍了,這裡是在不想再複製了,打個原始碼很簡單,大家直接看。

吐槽下:這個庫多了一道手,多加了一個檢視層級出來,其實沒必要在頂層加一個 viewGroup 了,直接繼承 ViewFlipper 可好

自定義 textView 思路

不繼承 textView 我們直接繼承 view 都可以,只要不支援 wrap_content 就好辦。 核心就是在 onDraw 中實現繪製的動畫。

例子這裡沒有使用 ValueAnimator 動畫,而是 1 個 px 變化就重繪一次,效能上欠考慮。

實現思路

1.根據文字,確定文字出螢幕的零界點

// 獲取文字矩陣的尺寸
Rect indexBound = new Rect();
mPaint.getTextBounds(text, 0, text.length(), indexBound);

// 文字居中繪製 Y 的座標
my = mHeight  / 2 - (bound.top + bound.bottom) / 2

// 文字移動到最頂部
mY == 0 - bound.bottom

// 文字移動到最下部
mY = mHeight  - indexBound.top;
複製程式碼

2.在 onDraw 中實現繪製

         // 文字首先繪製在最底部,mY 初始時 = 0
        if (mY == 0) {
            mY = getMeasuredHeight() - indexBound.top;
        }

        // 文字移動到最頂部時,更換資料,把文字移動到最底部
        if (mY == 0 - indexBound.bottom) {
            Log.i(TAG, "onDraw: " + getMeasuredHeight());
            mY = getMeasuredHeight() - indexBound.top;//返回底部
            mIndex++;//換下一組資料
        }

        // 文字移動到中間時,停止 handle 的重繪任務,延遲標準時間後再開始
        if (mY == getMeasuredHeight() / 2 - (indexBound.top + indexBound.bottom) / 2) {
            isMove = false;//停止移動
            // handle 通知標準時間後開始重繪
        }

        // 處理完 Y 座標,開始繪製文字
        canvas.drawText(font, 0, font.length(), 10, mY, mPaintFront);

        // 最後移動 1 個 px,以實現動畫效果
        mY -= 1
複製程式碼

這裡強調每移動 1個 px 就重繪一遍是為了確保動畫的連貫性,但是這樣系統也是 16 ms 才繪製一幀的,這樣高頻率的重繪並不是最優選擇哦



相關文章