Android實現(xiàn)文本逐字顯示View(類似rpg游戲人物對話,文本逐字顯示)

前面好多篇文章都是Android Studio、源碼編譯、ndk等相關教程,今天敲一敲代碼,不然都生銹了哈_

來個古裝動畫美圖,緩解大家疲勞的眼睛...(話說有木有人知道這是誰???)

Paste_Image.png

這是一個類似rpg游戲人物對話,文本逐字顯示的view,先上效果圖,不然大家都沒有興趣看下去,嘿嘿。

Demo地址:github(喜歡的可以運行看看)

showText3.gif

注:我錄制的gif是不是很清晰,想知道我用的是什么工具制作的嗎?_ (評論中有方法喔)

思路:想讓漢字、英文、數(shù)字、符號等逐個顯示,首先想到的是字符串處理,寫一個工具類拆分漢字、英文、數(shù)字、符號等,然后就是應用到Android的View上了,View上的實現(xiàn)其實很low,就是先使用工具類拆分一篇文本,然后將使用遞歸每隔300毫秒(時間可以修改)將文本畫到View的Canvas上;大體思路就是這樣。

注:不知道有沒有已經(jīng)造好輪子,我在網(wǎng)上沒找到類似的。如果大家看過類似的又比較優(yōu)秀的實現(xiàn),麻煩在評論里發(fā)給我哈。

1.首先寫字符串工具類XTextUtils.java,拆分字符串,代碼如下:

/**
 * Created by zhangyipeng on 16/3/16.
 */
public class XTextUtils {
    private static final String TAG = "XTextUtils";

    public static ArrayList<String> getContentList(String content) {
        ArrayList<String> list = new ArrayList<>();
        String s = "";
        String n = "";
        int sn = 0;
        content+=" ";
        int len = (content).length();

        for (int i = 0; i < len; i++) {

            char c = content.charAt(i);
            char c_1 = ' ';
            if(i>=1) {
                c_1 = content.charAt(i - 1);
            }
            if (isEnglish(c + "") || (isEnglish(c_1+"") && (c+"").equals("'"))) {
                s += c;
                sn = 1;
            }else if (isNumber(c + "") || (isNumber(c_1+"") && (c+"").equals("."))) {
                n += c;
                sn = 2;
            } else {
                if (!s.equals("") && !n.equals("") & sn==1) {
                    list.add(n+s);

                }else if (!s.equals("") && !n.equals("") & sn==2) {
                    list.add(s+n);

                }else if (!s.equals("") && n.equals("")) {
                    list.add(s);
                }else if (!n.equals("") && s.equals("")) {
                    list.add(n);
                }
                list.add(c + "");
                sn = 0;
                n = "";
                s = "";

            }
        }
        return list;
    }

    public static boolean isEnglish(String s) {

        Pattern p = Pattern.compile("^[a-zA-Z]*$");
        Matcher m = p.matcher(s);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }


    public static boolean isNumber(String s) {

        Pattern p = Pattern.compile("^[0-9]*$");
        Matcher m = p.matcher(s);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isChinese(String s) {

        Pattern p = Pattern.compile("^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]*$");
        Matcher m = p.matcher(s);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }
}

我們使用網(wǎng)上的任意一篇文章測試,這個工具類,效果如下圖:

胡|歌|,|1982|年|9|月|20|日|出|生|于|上|海|市|徐|匯|區(qū)|,|中|國|內(nèi)|地|演|員|、|歌|手|、|制|片|人|。|1996|年|,|14|歲|的|胡|歌|便|成|為|上|海|教|育|電|視|臺|的|小|主|持|人|,|2001|年|考|入|上|海|戲|劇|學|院|表|演|系|。|2005|年|因|在|電|視|劇|《|仙|劍|奇|俠|傳|》|中|成|功|塑|造|了|豪|爽|深|情|的|“|李|逍|遙|”|一|角|而|成|名|,|并|演|唱|插|曲|《|六|月|的|雨|》|《|逍|遙|嘆|》|。|2009|年|在|“|80|后|新|生|代|娛|樂|大|明|星|”|評|選|中|獲|封|“|四|大|小|生|”|之|一|。|
|First| |Flight|
|Mr|.| |Johnson| |had| |never| |been| |up| |in| |an| |aerophane| |before| |and| |he| |had| |read| |a| |lot| |about| |air| |accidents|,| |so| |one| |day| |when| |a| |friend| |offered| |to| |take| |him| |for| |a| |ride| |in| |his| |own| |small| |phane|,| |Mr|.| |Johnson| |was| |very| |worried| |about| |accepting|.| |Finally|,| |however|,| |his| |friend| |persuaded| |him| |that| |it| |was| |very| |safe|,| |and| |Mr|.| |Johnson| |boarded| |the| |plane|.|
|His| |friend| |started| |the| |engine| |and| |began| |to| |taxi| |onto| |the| |runway| |of| |the| |airport|.| |Mr|.| |Johnson| |had| |heard| |that| |the| |most| |dangerous| |part| |of| |a| |flight| |were| |the| |take|-|off| |and| |the| |landing|,| |so| |he| |was| |extremely| |frightened| |and| |closed| |his| |eyes|.|
|After| |a| |minute| |or| |two| |he| |opened| |them| |again|,| |looked| |out| |of| |the| |window| |of| |the| |plane|,| |and| |said| |to| |his| |friend|,| |"|Look| |at| |those| |people| |down| |there|.| |They| |look| |as| |small| |as| |ants|,| |don't| |they|?|"|
|"|Those| |are| |ants|,|"| |answered| |his| |friend|.| |"|We're| |still| |on| |the| |ground|.|"| |
Paste_Image.png

2.好了下面開始自定義View類的coding了,代碼如下:

注:如果直接使用canvas.drawText()的話,很難根據(jù)屏幕的寬度自動換行,還好Andorid為我們提供了StaticLayout類,使用它可以輕松的實現(xiàn)文本自動換行,以及行間距、對其方式(居左對齊、居中對其、居右對齊)等。

/**
 * Created by zhangyipeng on 16/3/16.
 */
public class XTextView extends View {

    private TextPaint textPaint;
    private float density;
    private String textContent;
    private int textColor;
    private String textAlignment;
    private float textSize;
    private float textSpacingAdd;
    private float textSpacingMult;

    public XTextView(Context context) {
        this(context, null, 0);
    }

    public XTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public XTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.XTextView);
        textContent = a.getString(R.styleable.XTextView_textContent);
        textColor = a.getColor(R.styleable.XTextView_textColor, Color.BLACK);
        textAlignment = a.getString(R.styleable.XTextView_textXAlignment);
        textSize = a.getDimension(R.styleable.XTextView_textSize, 20);
        textSpacingAdd = a.getFloat(R.styleable.XTextView_textSpacingAdd, 0.0F);
        textSpacingMult = a.getFloat(R.styleable.XTextView_textSpacingMult, 1.0F);


        init();
    }


    public void setTextSize(float textSize) {
        this.textSize = textSize;
    }

    public void setTextSpacingAdd(float textSpacingAdd) {
        this.textSpacingAdd = textSpacingAdd;
    }

    public void setTextSpacingMult(float textSpacingMult) {
        this.textSpacingMult = textSpacingMult;
    }

    public void setTextColor(int textColor) {
        this.textColor = textColor;
    }

    public void setTextAlignment(String textAlignment) {
        this.textAlignment = textAlignment;
    }

    public void setTextContent(final String content) {
        new Thread(){
            @Override
            public void run() {
                super.run();
                contents = XTextUtils.getContentList(content);
            }
        }.run();

    }

    private ArrayList<String> contents;

    private void init() {

        density = getResources().getDisplayMetrics().density;

        textPaint = new TextPaint();
        textPaint.setColor(textColor);
        textPaint.setTextSize(textSize);


    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        drawText(canvas);
    }

    private int cnt = 0;
    private String totalText = "";

    private void drawText(Canvas canvas) {

        if (cnt >= contents.size()) {
            return;
        }
        totalText += contents.get(cnt);
        StaticLayout layout = null;
        if (textAlignment.equals("normal")) {
            //textPaint(TextPaint 類型)設置了字符串格式及屬性的畫筆,240為設置畫多寬后換行,后面的參數(shù)是對齊方式及行間距
            layout = new StaticLayout(totalText, textPaint, getWidth() - (int) (20 * density), Layout.Alignment.ALIGN_NORMAL, textSpacingMult, textSpacingAdd, true);
        } else if (textAlignment.equals("center")) {
            layout = new StaticLayout(totalText, textPaint, getWidth() - (int) (20 * density), Layout.Alignment.ALIGN_CENTER, textSpacingMult, textSpacingAdd, true);
        } else if (textAlignment.equals("opposite")) {
            layout = new StaticLayout(totalText, textPaint, getWidth() - (int) (20 * density), Layout.Alignment.ALIGN_OPPOSITE, textSpacingMult, textSpacingAdd, true);

        }

        //從 (10,10)的位置開始繪制
        canvas.translate(10 * density, 10 * density);

        layout.draw(canvas);

        cnt++;

        startText();
    }

    public void startText() {
        if (cnt != contents.size()) {

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    invalidate();
                }
            }, time);
        }
    }

    private long time = 200;

    public void setDelayPlayTime(long time) {
        this.time = time;
    }
}

3.接下來就是調(diào)用了,運行了,如下圖

layout文件如下

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.zhangyipeng.graduallyshowtext.TargetActivity">

    <com.example.zhangyipeng.gradually_show_text.view.XTextView
        android:id="@+id/xtv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:textXAlignment="normal"
        app:textColor="#ff003b"
        app:textSize="20sp"
        app:textContent="你好"
        app:textSpacingMult="1.5"
        app:textSpacingAdd="0.0"
        />
</RelativeLayout>

Paste_Image.png

4.運行效果如下(再貼一次哈):

showText3.gif

Demo地址:github

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容