如何在 TextView 中逐字显示句子?
How to display a sentence word by word in a TextView?
我试过这段代码,但它只显示最后一个字:
signButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String speech = "This code is sample";
String[] result = speech.split("\s");
for (int x=0; x<result.length; x++) {
textView.setText(result[x]);
}
}
});
另一种方法
全局声明一个字符串 var
String s="";
现在在你的代码中使用这个
在 for 循环内
s=s+""+result[x];
textView.append(s):
textview 将只显示最后一个单词,因为它处于 for 循环中。设置每个单词后,下一次迭代将发生,因此用户只能查看最后一个单词。您可以在特定时间后更改每个单词。试试下面的代码。在这里我给了 5 秒来显示每个单词。
int x; //declare x as global variable
String speech = "This code is sample";
String[] result = speech.split("\s");
textView.setText(result[0]);
for (x=1; x<result.length; x++) {
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
textView.setText(result[x]);
}
}, 5000);
}
好的,首先我花了一些时间来理解您的问题,我仍然不确定,据我了解,您希望在单击按钮时显示在 textView 中添加的下一个 WORD。 . .
为此,您可以使用以下代码。
//String Array preparation
String speech = "This code is sample";
String[] result = speech.split("\s");
int count = 0;
signButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//check if array has more values to add or whatever you want to check
if(count<result.length){
if(count==0){
textView.append(result[count];
} else {
textView.append(" " + result[count];
}
count++;
}
}
});
我试过这段代码,但它只显示最后一个字:
signButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String speech = "This code is sample";
String[] result = speech.split("\s");
for (int x=0; x<result.length; x++) {
textView.setText(result[x]);
}
}
});
另一种方法 全局声明一个字符串 var
String s="";
现在在你的代码中使用这个 在 for 循环内
s=s+""+result[x];
textView.append(s):
textview 将只显示最后一个单词,因为它处于 for 循环中。设置每个单词后,下一次迭代将发生,因此用户只能查看最后一个单词。您可以在特定时间后更改每个单词。试试下面的代码。在这里我给了 5 秒来显示每个单词。
int x; //declare x as global variable
String speech = "This code is sample";
String[] result = speech.split("\s");
textView.setText(result[0]);
for (x=1; x<result.length; x++) {
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
textView.setText(result[x]);
}
}, 5000);
}
好的,首先我花了一些时间来理解您的问题,我仍然不确定,据我了解,您希望在单击按钮时显示在 textView 中添加的下一个 WORD。 . .
为此,您可以使用以下代码。
//String Array preparation
String speech = "This code is sample";
String[] result = speech.split("\s");
int count = 0;
signButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//check if array has more values to add or whatever you want to check
if(count<result.length){
if(count==0){
textView.append(result[count];
} else {
textView.append(" " + result[count];
}
count++;
}
}
});