我目前正在开发一个应用程序,该应用程序从一氧化碳传感器接收蓝牙数据,然后将其显示到用户的手机上。我的蓝牙方面正在工作,并且正在接收我需要的数据,但是,当尝试将变量显示到 TextView 元素时,该元素不会更新它只是保持不变。
屏幕上的按钮(在下面的 xml 中)将触发另一个模块来启动蓝牙通信,然后应该显示在屏幕上。这是按钮和 TextView 的 xml
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="350dp"
android:layout_marginBottom="160dp"
android:gravity="center"
**android:onClick="onStart"**
android:text="Start"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:id="@+id/textViewCO"
android:layout_width="53dp"
android:layout_height="14dp"
android:layout_marginEnd="350dp"
android:layout_marginBottom="408dp"
**android:text="Test"**
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
这是我当前为尝试完成这项工作而设置的代码。
while (btSocket.isConnected()) {
//reading the bluetooth input
info = inputStream.read(buffer);
//assigning read value from the buffer to a string
String readMessage = new String(buffer, 0, info);
//New textview object
TextView tv = (TextView) findViewById(R.id.textViewCO);
//Display variable
tv.setText(readMessage);
//Console log
System.out.println(readMessage);
try {
Thread.sleep(3200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
我已经尝试过了。我尝试过简单地显示文本,例如
tv.setText("This is some text");
但是这也不会改变任何事情。如果您需要任何其他代码或信息,请告诉我。
最佳答案
似乎您正在线程中运行代码,有时这会影响用户界面的性能,请尝试使用异步任务,如果失败,请尝试使用scrollBy方法执行代码后滚动父 View 。
关于java - Android studio TextView 值不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61000870/