gpt4 book ai didi

java - 如何延迟在 TextView 中显示文本(逐字逐句)

转载 作者:太空宇宙 更新时间:2023-11-03 12:54:24 25 4
gpt4 key购买 nike

我希望 TextView 中的文本逐字显示,甚至逐字母显示,就像在大多数带有文本框的角色扮演游戏和冒险游戏中一样。一个很好的例子就是文本流应该是什么样子的游戏 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;
}
}

然后像这样在你的 Activity 中使用上面的类:

    Typewriter writer = new Typewriter(this);
//Add a character every 200ms
writer.setCharacterDelay(200);
writer.animateText("Sample String");

关于java - 如何延迟在 TextView 中显示文本(逐字逐句),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23405511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com