您的位置:首页 > 其它

让文字实现在控件上的逐字显示(TextView为例)

2016-04-13 09:29 155 查看
刚来家新公司,看到需求文档里面有这么一条,就是让文字在控件上面逐字显示出来,于是就动手写了一下,我这里是用TextView为例子的,废话不说了,直接上代码!

<pre name="code" class="java">package com.example.testdemo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

protected static final int UI = 100;
private String TextDemo = "我是一段测试文字我是一段测试文字我是一段测试文字我是一段测试文字我是一段测试文字我是一段测试文字我是一段测试文字";
private TextView text;
private char[] charArrays;
private String len = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
text = (TextView) findViewById(R.id.text);
new Thread(){
public void run() {
try {
charArrays = TextDemo.toCharArray();
for (int i = 0; i < charArrays.length; i++) {
sleep(100);
len = charArrays[i]+"";
handler.sendEmptyMessage(UI);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case UI:
text.append(len);
break;

default:
break;
}
}

};
}



</pre><pre name="code" class="java">还有一个方法,就是用做淡入淡出动画的方式,代码也很简单,上代码:
</pre><pre name="code" class="java"><pre name="code" class="java">@Override
protected void onCreate(Bundle savedInstanceState) {

setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);

text = (TextView) findViewById(R.id.text);

text.setText(TextDemo);

AnimationSet animationSet = new AnimationSet(true);

AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);

alphaAnimation.setDuration(3000);

animationSet.addAnimation(alphaAnimation);

text.startAnimation(animationSet);

}





其实这不是很难,就是当时在想的时候忘记了怎么把字符串改成Character,还有就是,TextView的append方法,只能添加String类型的数据,要是字符型的他是不支持的,所以就得在后面加上一个双引号,嗯....大概也就这么多了,大家有什么好的建议的也可以跟我留言啊!在此谢过大家!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: