如何每5秒在值之间切换TextView

时间:2019-05-28 11:22:36

标签: java android textview android-runonuithread

我不知道使用 Threads 是否是我要达到的目的的做法,所以请随时在所需的地方修改代码。

我正在尝试在我的应用程序中实现一项功能,其中TextView会切换为1值,然后每5秒恢复到初始值。我已经在线程上使用以下代码:

    layoutDate.setText(firstNumber);

    Thread numberSwitch = new Thread() {
    @Override
    public void run() {
        while(!isInterrupted()) {
            try {

                Thread.sleep(5000);

                runOnUiThread(new Runnable () {
                    @Override
                    public void run() {

                        layoutDate.setText(secondNumber);                   

                    }
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }       
    }
};

numberSwitch.start();

我尝试在layoutDate.setText(firstNumber)之后以及嵌套的runUiOnThread之后添加run,但仍然无法按我的意愿工作。

我想要实现以下目标:

Example

2 个答案:

答案 0 :(得分:1)

您可以将Handler与可运行对象一起使用。

private TextView textView;
private Handler handler;

在您的onCreate()

textView = findViewById(R.id.tv_bt_msg);
textView.setText("secondNumber");

handler = new Handler();
//Change the textview after 5 seconds
handler.postDelayed(runnable, 5000);

可以每5秒钟更改一次文字

private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            String currentString = textView.getText().toString();
            if(currentString.equals("secondNumber")){
                currentString = "firstNumber";
            }else{
                currentString = "secondNumber";
            }
            final String tempString = currentString;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textView.setText(tempString);
                }
            });
            //Change the textview again after 5 seconds
            handler.postDelayed(runnable, 5000);
        }
    };

使用它来删除回调

handler.removeCallbacks(runnable);

答案 1 :(得分:0)

验证字段中的当前数字并更改为其他数字,您可以通过获取值layoutDate.getText().toString()或使用新变量来存储值来实现。

layoutDate.setText(firstNumber);

    Thread numberSwitch = new Thread() {
    @Override
    public void run() {
        while(!isInterrupted()) {
            try {

                Thread.sleep(5000);

                runOnUiThread(new Runnable () {
                    @Override
                    public void run() {

                        if(currentNumber == firstNumber){
                            currentNumber = secondNumber;
                        }else{
                            currentNumber = firstNumber;
                        }
                        layoutDate.setText(currentNumber);
                    }
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }       
    }
};

numberSwitch.start();

if(layoutDate.getText().toString().equals(firstNumber+"")){
    layoutDate.set(secondNumber);
}else{
    layoutDate.set(firstNumber);
}