文字一个个出现的TextView

本文介绍了一个自定义TextView组件,能够实现文本逐字显示效果。通过继承TextView并利用Canvas和Paint,控制文本逐个绘制到屏幕上,营造类似打字机的效果。文章提供了完整的代码示例及使用说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近自己折腾了个小玩意儿,其中有个需求是让文本一个个的出现在界面上,实现类似打字的效果。先看效果图
效果
实现起来很简单,先上代码

package com.example.typertext;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

public class TyperTextView extends TextView {

    private Paint mPaint;
    private int currentStrLength;
    private int currentStrIndex;
    /**
     * 当前文字的大小
     */
    private float mTextSize;
    private float startX = 0;
    private float startY = 0;
    /**
     * 存储分割后的文本信息
     */
    private String[] str;

    /**
     * 行距
     */
    private float rowSpacing = 60;

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

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

    public TyperTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 初始化基本信息
     * 
     */
    private void init(String text) {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(this.getCurrentTextColor());
        mPaint.setStyle(Paint.Style.FILL);

        str = text.split("--");

        mTextSize = this.getTextSize();

        mPaint.setTextSize(mTextSize);

        startX = (this.getMeasuredWidth() - this.getCompoundPaddingLeft()
                - this.getPaddingLeft() - mPaint.measureText(str[0])) / 2f;
        startY = this.getBaseline();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        init(this.getText().toString());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        drawFrame(canvas);
    }

    //设置文本
    public void setMyText(String myText) {
        init(myText);
        this.postInvalidateDelayed(100);
    }

    protected void drawFrame(Canvas canvas) {
        for (int i = 0; i <= currentStrIndex; i++) {
            if (i < currentStrIndex) {
                canvas.drawText(str[i], 0, str[i].length(), startX, startY
                        + rowSpacing * i, mPaint);
            } else {
                canvas.drawText(str[i], 0, currentStrLength, startX, startY
                        + rowSpacing * i, mPaint);
            }
        }
        if (currentStrLength < str[currentStrIndex].length()) {
            currentStrLength++;
            this.postInvalidateDelayed(100);
        } else if (currentStrIndex < str.length - 1) {
            currentStrLength = 0;
            currentStrIndex++;
            this.postInvalidateDelayed(100);
        }

    }

}

首先,继承TextView,我选择在onSizeChange()方法里面初始化我们所需的参数,因为我们的参数有一些涉及到了长宽之类测量,在初始化参数的init()方法里面,我们将传进来的文字以“–”为分隔符分割成一个字符串数组,然后在drawFrame(Canvas canvas)方法里面循环遍历该数组,通过currentStrIndex和currentStrLength 两个参数来控制显示在屏幕上的文字,使得每次显示在屏幕上的文字都比上一次多一个,随后调用canvas.drawText(..)方法将满足条件的文字显示在屏幕上,随后通过postInvalidateDelayed(long delayMilliseconds)方法来通知应用在固定时间后刷新界面,这样一次次的刷新界面就实现了文字的逐个显示

使用举例:
首先是布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="开始" />


    <com.example.typertext.TyperTextView
        android:id="@+id/ttv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="" />

</LinearLayout>

接着是Activity

package com.example.typertext;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
    private TyperTextView typerTextView;
    private Button start;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        typerTextView = (TyperTextView) findViewById(R.id.ttv);
        start = (Button) findViewById(R.id.start);
        start.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
            //"--"是换行符,表示换行
                typerTextView
                        .setMyText("临安初雨,一夜落红--春水凝碧,断雁越澄空--挥袖抚琴,七弦玲珑--芦苇客舟,雨朦胧--那年竹楼,惘然如梦--纤指红尘,醉影笑惊鸿 ");
            }
        });
    }

}

“–”在这里起到的是换行符的效果,当然你也可以选择将文字直接写到布局文件里面,效果一样。

这个控件的实现参考了开源框架HTextView:https://github.com/hanks-zyh/HTextView,是很不错的一个文本特效框架,有兴趣的可以看看
感谢作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值