简体   繁体   English

Android Java:每x秒更新一次TextView,无需用户输入

[英]Android Java: Update a TextView every x seconds without user input

I'm making an app in Android Java, using Android Studio. 我正在使用Android Studio使用Android Java开发应用程序。 Every 0.1 seconds I want to update the text within a certain TextView. 我想每隔0.1秒更新某个TextView中的文本。

I already managed to use a Handler to execute a method every 0.1 seconds (100 ms), but it doesn't automatically update the TextView. 我已经设法使用处理程序每​​0.1秒(100毫秒)执行一个方法,但是它不会自动更新TextView。

It only updates the TextView to what I want when the user interacts with the app. 当用户与应用程序交互时,它只会将TextView更新为我想要的内容。 It only updates it when, for example, the user slides the SeekBar or presses a button. 仅在例如用户滑动SeekBar或按下按钮时才更新它。 It doesn't update when the user clicks on the screen, and not automatically without input either. 用户单击屏幕时它不会更新,并且也不会在没有输入的情况下自动更新。

How can I make it such that it will update the value automatically, without user input? 我如何才能使其无需用户输入即可自动更新值?

Thanks in advance. 提前致谢。

PS: I'm new to Android and Java, and I'm using threads to get the value, in xml format, from a website. PS:我是Android和Java的新手,我正在使用线程从网站获取xml格式的值。

Should I post any code, and if so, what exactly? 我应该发布任何代码吗?

you can try updating the value of text view on the UI thread. 您可以尝试在UI线程上更新文本视图的值。

 runOnUiThread(new Runnable() {
        @Override
        public void run() {
            //update TextView here
        }
    });
Thread t = new Thread() {
        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(100);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // update TextView here!
                        }
                    });
                }
            } catch (InterruptedException e) {
            }
        }
    };

    t.start();

You can update your textview using thread also, like this. 您也可以像这样使用线程更新textview。

 int prStatus = 0;
 new Thread(new Runnable() {
        public void run() {
            while (prStatus < 100) {
                prStatus += 1;
                handler.post(new Runnable() {
                    public void run() {
                        tv.setText(prStatus + "/");
                    }
                });
                try {
                    Thread.sleep(150);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if(prStatus == 100)
                    prStatus = 0;
            }
        }
    }).start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM