java - Android studio TextView 值不会更新

标签 java android android-studio android-layout textview

我目前正在开发一个应用程序,该应用程序从一氧化碳传感器接收蓝牙数据,然后将其显示到用户的手机上。我的蓝牙方面正在工作,并且正在接收我需要的数据,但是,当尝试将变量显示到 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/

相关文章:

java - RMI 序列化/编码

java - 有没有一种方法可以在 Java 8+ 中指定嵌套泛型而不需要两次指定类型

android - 如何使用 LibGdx 在 Tilemap 中制作动画?

c# - Xamarin Android - 如何将事件从 MainActivity 传递到表单页面上的 ViewModel?

Java 数据类型到 Swift,反之亦然

android 在后退按钮上点击 Action

java - 倒计时器显示 toast 一半时间

Android Studio 无线 ADB 错误 (10061)

进行适当更新后,Android View 绑定(bind)弃用警告在 Android Studio 4 中仍然存在

java - 为 JButton 添加全局键绑定(bind)?