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

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

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

Paste_Image.png

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

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

showText3.gif

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

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

注:不知道有沒有已經(jīng)造好輪子,我在網(wǎng)上沒找到類似的。如果大家看過類似的又比較優(yōu)秀的實(shí)現(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|年|考|入|上|海|戲|劇|學(xué)|院|表|演|系|。|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類,使用它可以輕松的實(shí)現(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 類型)設(shè)置了字符串格式及屬性的畫筆,240為設(shè)置畫多寬后換行,后面的參數(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)用了,運(yùn)行了,如下圖

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.運(yùn)行效果如下(再貼一次哈):

showText3.gif

Demo地址:github

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,578評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,701評論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,691評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,974評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,694評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,026評論 1 329
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,015評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,193評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,719評論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,442評論 3 360
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,668評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,151評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,846評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,255評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,592評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,394評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,635評論 2 380

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