我想在文本视图中显示数据 2 秒钟。所以我从arduino收到了数据,这些数据在我使用串行写之间没有延迟。我使用InputStream和DatainputStream来接收接收数据。当数据显示在文本视图中时,它仍然存在问题。它将有机会突然出现下一个数据。有什么方法可以保持它 2 秒并有机会进入下一个?我在安卓工作室写代码。 .
private void receive(byte[] data) {
InputStream is = null;
DataInputStream dis = null;
try {
is = new ByteArrayInputStream(data);
dis = new DataInputStream(is);
while (dis.available() > 0) {
byte[] b = new byte[data.length];
dis.read(b, 0, 8);
count++;
String part = HexDump.dumpHexString(b).substring(HexDump.dumpHexString(b).indexOf("E7 0"), HexDump.dumpHexString(b).indexOf("0A"));
if (part.contains("E7 01")) {
//receive_text2.setText((part));
show_text(receive_text2,part);
}
if (part.contains("E7 02")) {
receive_text3.setText(String.valueOf(1000*unsiged(b[5])+100*unsiged(b[6])));
}
if (part.contains("E7 03")) {
receive_text4.setText((part));
}
if (part.contains("E7 05")) {
receive_text5.setText((part));
}
receive_text6.setText(String.valueOf(count));
}
}catch (Exception e){
receive_text2.append("");
receive_text3.append("");
receive_text4.append("");
receive_text5.append("");
receive_text6.append("");
}
}
每次尝试设置文本值时,可以尝试使用 Handler 发布 2 秒(2000 毫秒(的延迟。
TextView textView = ...;
textView.postDelayed(new Runnable() {
@Override
public void run() {
textView.setText("some text");
}
}, 2000); // delay of 2 seconds before setting a text to textView
将所有要显示的字符串添加到数组列表中
ArrayList<String> strings = new ArrayList<>();
然后做:
Runnable job = new Runnable() {
@Override
public void run() {
if (!strings.isEmpty()) {
textView.setText(strings.get(0));
strings.remove(0);
textView.postDelayed(this, 2000);
} else {
textView.removeCallbacks(this);
}
}
};
textView.postDelayed(job, 2000); // delay of 2 seconds before setting a text to textView