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

自定義 View 打造垂直跑馬燈:完整思路與程式碼解析

編輯:關於 Android 程式設計

先看效果:

畫面中間的色塊是影片轉 GIF 造成的失真,可以忽略。

大家都熟悉,水平方向的跑馬燈用 Android 原生的 TextView 加上跑馬燈屬性就能搞定;但垂直方向的捲動,原生控制項並不支援。網路上雖然有不少人寫過自定義版本,這篇則是完全依照自己的思路重新設計,並把每一步的設計理由寫清楚。

一、先把版面結構想清楚

整個自定義控制項的設計要點如下:

1、把控制項在概念上切成三塊:上方綠色區域是「已消失、不可見」的部分,中間黑色區域是「可見區」,下方紅色區域是「即將出現、目前不可見」的部分。藍線代表控制項的上邊界與下邊界。

2、記憶體中隨時只保留兩個文字塊:黑色區域的當前可見塊,以及紅色區域的即將出現塊。

3、計算這兩個塊的寬、高與中心點座標。

4、捲動時,動態改變每個塊的中心點 y 座標,讓它整體向上位移。

5、位移結束後,原本的可見塊已進入上方不可見區,原本的「即將出現塊」則正好落在可見區。此時把要消失的文字塊移出 List,重新設定下一筆資料的文字與重心座標,再放回 List 並刷新畫面。

6、用 Handler 控制每次捲動的間隔節奏,用屬性動畫 ValueAnimator 負責位移的平滑過渡。

二、鏈式設定法配置基礎屬性

public VerticalMarqueeView color(int color) {
    this.color = color;
    return this;
}

public VerticalMarqueeView textSize(int textSize) {
    this.textSize = textSize;
    return this;
}

public VerticalMarqueeView datas(String[] datas) {
    this.datas = datas;
    return this;
}

public void commit() {
    if (this.datas == null || datas.length == 0) {
        Log.e("VerticalMarqueeView", "the datas's length is illegal");
        throw new IllegalStateException("may be not invoke the method named datas(String[])");
    }
    paint.setColor(color);
    paint.setTextSize(textSize);
}

最後一定要呼叫 commit() 提交設定。從程式碼可以看出,這裡除了有空值檢查,還有一個關鍵動作:設定字型大小。若不呼叫 commit(),畫筆的顏色與字級都不會生效。

三、抽象出文字塊 TextBlock

public class TextBlock {
    private int width;
    private int height;
    private String text;
    private int drawX;
    private int drawY;
    private Paint paint;
    private int position;

    public TextBlock(int width, int height, Paint paint) {
        this.width = width;
        this.height = height;
        this.paint = paint;
    }

    public void reset(int centerY) {
        reset(text, centerX, centerY, position);
    }

    public void reset(String text, int centerY) {
        reset(text, centerX, centerY, position);
    }

    public void reset(String text, int centerY, int position) {
        reset(text, centerX, centerY, position);
    }

    public void reset(String text, int centerX, int centerY, int position) {
        this.text = text;
        this.position = position;
        int measureWidth = (int) paint.measureText(text);
        drawX = (width - measureWidth) / 2;
        FontMetrics metrics = paint.getFontMetrics();
        drawY = (int) (centerY + (metrics.bottom - metrics.top) / 2 - metrics.bottom);
    }

    public int getPosition() {
        return position;
    }

    public void draw(Canvas canvas) {
        canvas.drawText(text, drawX, drawY, paint);
    }
}

這個 bean 最重要的是幾個多載的 reset 方法:透過改變 centerY,動態調整文字繪製起點,達到水平與垂直雙重居中。關於 Canvas 文字居中的原理,可以另外參考相關的 FontMetrics 計算說明。

四、重新定義測量邏輯 onMeasure

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    if (this.datas == null || this.datas.length == 0) {
        Log.e("VerticalMarqueeView", "the datas's length is illegal");
        return;
    }
    width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
    height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom();
    centerX = width / 2;
    centerY = height / 2;
    blocks.clear();

    // 加入顯示區域的文字塊
    TextBlock block1 = new TextBlock(width, height, paint);
    block1.reset(datas[0], centerX, centerY, 0);
    blocks.add(block1);

    if (datas.length > 1) {
        TextBlock block2 = new TextBlock(width, height, paint);
        block2.reset(datas[1], centerX, centerY + height, 1);
        blocks.add(block2);
    }
}

這裡先做一次非空判斷,避免後續邏輯出致命錯誤;接著取得控制項的實際寬高與中心座標。然後建立兩個 TextBlock:第一個的中心 y 座標等於控制項中心,也就是可見位置;第二個的中心 y 座標為 centerY + height,正好落在下方的不可見區等待進場。

五、onDraw 只管委派繪製

@Override
protected void onDraw(Canvas canvas) {
    for (int i = 0; i < blocks.size(); i++) {
        blocks.get(i).draw(canvas);
    }
}

因為具體的繪製細節都已經封裝進 TextBlock,onDraw 就非常單純。

六、控制捲動節奏

public void startScroll() {
    isStopScroll = false;
    if (datas == null || datas.length == 0 || datas.length == 1) {
        Log.e("VerticalMarqueeView", "the datas's length is illegal");
        return;
    }
    if (!isStopScroll) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                scroll();
                if (!isStopScroll) {
                    handler.postDelayed(this, DURATION_SCROLL);
                }
            }
        }, DURATION_SCROLL);
    }
}

public void stopScroll() {
    this.isStopScroll = true;
}

原理很單純:一個 boolean 旗標 isStopScroll 作為開關,再用 Handler.postDelayed 週期性呼叫 scroll() 觸發一次捲動。

七、全篇核心:scroll 方法

private void scroll() {
    ValueAnimator animator = ValueAnimator.ofPropertyValuesHolder(
            PropertyValuesHolder.ofInt("scrollY", centerY, centerY - height));
    animator.setDuration(DURATION_ANIMATOR);
    animator.addUpdateListener(new AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            int scrollY = (int) animation.getAnimatedValue("scrollY");
            blocks.get(0).reset(scrollY);
            blocks.get(1).reset(scrollY + height);
            invalidate();
        }
    });
    animator.addListener(new AnimatorListener() {
        @Override public void onAnimationStart(Animator animation) { }
        @Override public void onAnimationRepeat(Animator animation) { }

        @Override
        public void onAnimationEnd(Animator animation) {
            // 移除第一塊
            int position = blocks.get(1).getPosition();
            TextBlock textBlock = blocks.remove(0);
            // 若已是最後一筆,回到開頭循環
            if (position == datas.length - 1) {
                position = 0;
            } else {
                position++;
            }
            textBlock.reset(datas[position], centerY + height, position);
            blocks.add(textBlock);
            invalidate();
        }

        @Override public void onAnimationCancel(Animator animation) { }
    });
    animator.start();
}

這裡用 ValueAnimator 做屬性動畫,起始值為控制項中心 y 座標,結束值為 centerY - height,也就是向上移動剛好一個文字塊的高度。動畫更新回呼中不斷呼叫兩個文字塊的 reset 並 invalidate() 重繪;動畫結束後,取出第二塊的 position,把第一塊移出佇列、重新指定下一筆資料與座標,再放回容器。如此循環,就形成了無縫的垂直輪播。

八、對外取得目前索引

public int getCurrentPosition() {
    if (datas == null || datas.length == 0) {
        return -1;
    }
    if (datas.length == 1 && blocks.size() == 1) {
        return 0;
    }
    return blocks.get(0).getPosition();
}

九、完整原始碼

由於程式碼分散在幾個區塊,這裡把 VerticalMarqueeView.java 全文一次列出,方便直接複製使用:

package cc.wxf.component;

import android.animation.Animator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import java.util.ArrayList;
import java.util.List;

public class VerticalMarqueeView extends View {
    public static final int DURATION_SCROLL = 3000;
    public static final int DURATION_ANIMATOR = 1000;

    private int color = Color.BLACK;
    private int textSize = 30;
    private String[] datas = null;
    private int width;
    private int height;
    private int centerX;
    private int centerY;
    private List<TextBlock> blocks = new ArrayList<TextBlock>(2);
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Handler handler = new Handler();
    private boolean isStopScroll = false;

    public VerticalMarqueeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public VerticalMarqueeView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public VerticalMarqueeView(Context context) {
        super(context);
    }

    public VerticalMarqueeView color(int color) {
        this.color = color;
        return this;
    }

    public VerticalMarqueeView textSize(int textSize) {
        this.textSize = textSize;
        return this;
    }

    public VerticalMarqueeView datas(String[] datas) {
        this.datas = datas;
        return this;
    }

    public void commit() {
        if (this.datas == null || datas.length == 0) {
            Log.e("VerticalMarqueeView", "the datas's length is illegal");
            throw new IllegalStateException("may be not invoke the method named datas(String[])");
        }
        paint.setColor(color);
        paint.setTextSize(textSize);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (this.datas == null || this.datas.length == 0) {
            Log.e("VerticalMarqueeView", "the datas's length is illegal");
            return;
        }
        width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
        height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom();
        centerX = width / 2;
        centerY = height / 2;
        blocks.clear();

        TextBlock block1 = new TextBlock(width, height, paint);
        block1.reset(datas[0], centerX, centerY, 0);
        blocks.add(block1);

        if (datas.length > 1) {
            TextBlock block2 = new TextBlock(width, height, paint);
            block2.reset(datas[1], centerX, centerY + height, 1);
            blocks.add(block2);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        for (int i = 0; i < blocks.size(); i++) {
            blocks.get(i).draw(canvas);
        }
    }

    public void startScroll() {
        isStopScroll = false;
        if (datas == null || datas.length == 0 || datas.length == 1) {
            Log.e("VerticalMarqueeView", "the datas's length is illegal");
            return;
        }
        if (!isStopScroll) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    scroll();
                    if (!isStopScroll) {
                        handler.postDelayed(this, DURATION_SCROLL);
                    }
                }
            }, DURATION_SCROLL);
        }
    }

    public void stopScroll() {
        this.isStopScroll = true;
    }

    private void scroll() {
        ValueAnimator animator = ValueAnimator.ofPropertyValuesHolder(
                PropertyValuesHolder.ofInt("scrollY", centerY, centerY - height));
        animator.setDuration(DURATION_ANIMATOR);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int scrollY = (int) animation.getAnimatedValue("scrollY");
                blocks.get(0).reset(scrollY);
                blocks.get(1).reset(scrollY + height);
                invalidate();
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                int position = blocks.get(1).getPosition();
                TextBlock textBlock = blocks.remove(0);
                if (position == datas.length - 1) {
                    position = 0;
                } else {
                    position++;
                }
                textBlock.reset(datas[position], centerY + height, position);
                blocks.add(textBlock);
                invalidate();
            }
        });
        animator.start();
    }

    public int getCurrentPosition() {
        if (datas == null || datas.length == 0) {
            return -1;
        }
        if (datas.length == 1 && blocks.size() == 1) {
            return 0;
        }
        return blocks.get(0).getPosition();
    }

    public class TextBlock {
        private int width;
        private int height;
        private String text;
        private int drawX;
        private int drawY;
        private Paint paint;
        private int position;

        public TextBlock(int width, int height, Paint paint) {
            this.width = width;
            this.height = height;
            this.paint = paint;
        }

        public void reset(int centerY) {
            reset(text, centerX, centerY, position);
        }

        public void reset(String text, int centerY) {
            reset(text, centerX, centerY, position);
        }

        public void reset(String text, int centerY, int position) {
            reset(text, centerX, centerY, position);
        }

        public void reset(String text, int centerX, int centerY, int position) {
            this.text = text;
            this.position = position;
            int measureWidth = (int) paint.measureText(text);
            drawX = (width - measureWidth) / 2;
            FontMetrics metrics = paint.getFontMetrics();
            drawY = (int) (centerY + (metrics.bottom - metrics.top) / 2 - metrics.bottom);
        }

        public int getPosition() {
            return position;
        }

        public void draw(Canvas canvas) {
            canvas.drawText(text, drawX, drawY, paint);
        }
    }
}

十、在 Activity 中使用

package cc.wxf.androiddemo;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import cc.wxf.component.VerticalMarqueeView;

public class MainActivity extends Activity {
    private VerticalMarqueeView vmView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        vmView = (VerticalMarqueeView) findViewById(R.id.vmView);
        String[] datas = new String[]{
                "第一條測試訊息",
                "第二條測試訊息,長度稍有不同",
                "第三條測試訊息",
                "第四條測試訊息",
                "第五條測試訊息,用來驗證不同長度的排版",
                "第六條測試訊息"
        };
        vmView.color(getResources().getColor(android.R.color.black))
              .textSize(sp2px(this, 15))
              .datas(datas)
              .commit();
        vmView.startScroll();

        vmView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this,
                        "目前的索引為:" + vmView.getCurrentPosition(),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    private int sp2px(Context context, int sp) {
        float density = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (sp * density + 0.5f);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 必須呼叫,否則 Handler 迴圈會持續佔用記憶體
        vmView.stopScroll();
    }
}

整體而言,這個自定義控制項只靠一個 View 檔案就完成,移植成本很低。特別提醒 onDestroy() 中的 stopScroll() 一定要呼叫,否則 Handler 的延遲迴圈會造成記憶體洩漏。

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