使用仅显示最后更改的处理程序更新 TextVIew

Updating TextVIew with Handler only showing last change

我正在尝试每 3 秒使用不同的字符串更新一次 TextView。我有一个处理程序和 运行nable 设置,但是当我 运行 它时,它会自动显示最后一个 setText。我尝试过将 ms 更改为 3000、6000 等,并且还在 运行ning 之前尝试过 removeCallbacks。任何帮助将不胜感激!

final Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.workout);

    final Runnable r = new Runnable(){
        @Override
        public void run(){
            TextView text = (TextView)findViewById(R.id.textView4);
            text.setText("1");
            handler.postDelayed(this, 3000);
            text.setText("2");
            handler.postDelayed(this, 3000);
            text.setText("3");
            handler.postDelayed(this, 3000);
            text.setText("4");
            handler.postDelayed(this, 3000);
            text.setText("5");


        }
    };

    handler.postDelayed(r, 0);


}

像这样更改您的代码

private String[] messages = {"1", "2", "3", "4", "5"};
    final Handler handler = new Handler();
    private int nextIndex;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.workout);
        final TextView text = (TextView)findViewById(R.id.textView4);
        final Runnable r = new Runnable(){
            @Override
            public void run(){
                if (messages.length > nextIndex) {
                    text.setText(messages[nextIndex++]);
                    handler.postDelayed(this, 3000);
                }
            }
        };

        handler.postDelayed(r, 0);
    }