javaandroidtextviewandroid-runonuithread

How to switch TextView between values every 5 seconds


I don't know if using Threads is the practice for what I am trying to achieve so please feel free to amend the code where you wish.

I am trying to implement a feature in my app where a TextView switches to 1 value and thereafter reverts back to the initial value every 5 seconds. I have implemented the following using on a thread:

    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();

I have tried adding layoutDate.setText(firstNumber) just after the runUiOnThread and also after the nested run but it still doesn't work as I want it to.

I want to achieve something like the following:

Example


Solution

  • You can use Handler with a runnable.

    private TextView textView;
    private Handler handler;
    

    in your onCreate()

    textView = findViewById(R.id.tv_bt_msg);
    textView.setText("secondNumber");
    
    handler = new Handler();
    //Change the textview after 5 seconds
    handler.postDelayed(runnable, 5000);
    

    Runnable to change text every 5 seconds

    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);
            }
        };
    

    Use this to removeCallbacks

    handler.removeCallbacks(runnable);