如何在TextView中延迟显示文本(逐字逐句)
作者:互联网
我希望TextView中的Text可以逐字显示,甚至可以逐字母显示,就像大多数rpgs和带有文本框的冒险一样.文本流应该是什么样子的一个很好的例子是游戏phoenix wright(http://youtu.be/2OOX2Gv0768?t=1m7s)
我到现在为止尝试的是:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String text = "test test test test";
String[] split = text.split(" ");
Deque<String> words = new LinkedList<String>();
for (int i = 0; i<split.length; i++)
{
words.addLast(split[i]);
}
showNextWord(words);
}
public void showNextWord(final Deque<String> words)
{
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
public void run()
{
TextView t = (TextView) findViewById(R.id.textBox);
t.append(words.pollFirst()+" ");
if (words.size()>0)
showNextWord(words);
}
}, 500);
}
我在模拟器上进行了测试,它似乎性能较低,如果我在显示每个字母后开始延迟,则更多.延迟不一致.
除此之外,我希望有一个更优雅的解决方案.也许某种方式可以更加灵活地延迟?例如.判刑后延误等等.
非常感谢你!
解决方法:
public class Typewriter extends TextView {
private CharSequence mText;
private int mIndex;
private long mDelay = 500; //Default 500ms delay
public Typewriter(Context context) {
super(context);
}
public Typewriter(Context context, AttributeSet attrs) {
super(context, attrs);
}
private Handler mHandler = new Handler();
private Runnable characterAdder = new Runnable() {
@Override
public void run() {
setText(mText.subSequence(0, mIndex++));
if(mIndex <= mText.length()) {
mHandler.postDelayed(characterAdder, mDelay);
}
}
};
public void animateText(CharSequence text) {
mText = text;
mIndex = 0;
setText("");
mHandler.removeCallbacks(characterAdder);
mHandler.postDelayed(characterAdder, mDelay);
}
public void setCharacterDelay(long millis) {
mDelay = millis;
}
}
并在您的活动中使用上面的类,如下所示:
Typewriter writer = new Typewriter(this);
//Add a character every 200ms
writer.setCharacterDelay(200);
writer.animateText("Sample String");
标签:android,java,performance,textview,adventure 来源: https://codeday.me/bug/20190830/1771062.html