Android Studio Java更新循环中的文本 [英] Android studio Java update text in the loop

查看:95
本文介绍了Android Studio Java更新循环中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次在这里学习编码语言.我在Java的许多部分中苦苦挣扎,但我正在慢慢学习.

first time learning coding language here.. I am struggling in many parts of Java, but I am slowly learning.

我正在制作一个应用程序,并且必须显示动态更新的文本.所以下面的代码是我的尝试,它工作得很好(有点).问题在于,在程序运行for循环时,它不会更新屏幕.

I was making an app and had to show dynamically updating text. So the below code is my attempt, it works very well (sort of). The problem is that it does not update the screen while program is running the for loop.

因此,当我从主要活动中按下按钮时,它将运行一个名为玩"的活动.它有14个文本字段,为0,应将它们自动一一更新为7.

So when I press a button from main activity, it runs an activity called play. It has 14 text fields of 0, and should update them to 7 one by one automatically.

但是在运行下面的代码后,稍后显示14个7s.(也没有0开头!)显示屏幕的任何代码,以便我可以将其放在setText()下?

But after running the code below, it just shows fourteen 7s after a moment. (no 0s to start with too!) Any code for showing the screen so that I can put it under setText() ?

很抱歉,以前是否有人问过这个问题,但是我真的找不到在线答案.

I am sorry if this question was asked before but I really couldn't find any answer online.

public class Play extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_play);
    Initialization();
}

public void Initialization() {
    TextView[] textViews = new TextView[] {
            (TextView)findViewById(R.id.player1_1),
            (TextView)findViewById(R.id.player1_2),
            (TextView)findViewById(R.id.player1_3),
            (TextView)findViewById(R.id.player1_4),
            (TextView)findViewById(R.id.player1_5),
            (TextView)findViewById(R.id.player1_6),
            (TextView)findViewById(R.id.player1_7),

            (TextView)findViewById(R.id.player2_1),
            (TextView)findViewById(R.id.player2_2),
            (TextView)findViewById(R.id.player2_3),
            (TextView)findViewById(R.id.player2_4),
            (TextView)findViewById(R.id.player2_5),
            (TextView)findViewById(R.id.player2_6),
            (TextView)findViewById(R.id.player2_7)
    };
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 14; j++) {
            textViews[j].setText(Integer.toString(i));
            try {
                Thread.sleep(25);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

}

推荐答案

当前,您在UI线程上调用 Thread.sleep(25).这意味着UI线程将被阻止,并且不会更新您的文本视图.经过所有这些阻止之后,它最终会在for循环之后被取消阻止,因此您可以立即看到所有文本字段都在更新.

Currently, you call Thread.sleep(25) on the UI thread. This means that the UI thread will be blocked and will not update your text views. After all that blocking, it is finally unblocked after the for loop, so you can immediately see all the text fields updating.

要获得更好的用户体验,请不要让UI线程进入睡眠状态.

For better user experience, never tell the UI thread to sleep.

您需要一些可以在一段时间后完成一些工作的东西. android.os.Handler 是一个不错的选择.它具有 postDelayed 方法,该方法将在一段时间后执行您希望它执行的操作.

You need something that will do some work after an amount of time. android.os.Handler is a pretty good choice. It has a postDelayed method that will do the thing you want it to do after some time.

IMO,直接调用 postDelayed 确实可以完成您的工作.但是每个 postDelayed 调用都包含另一个调用,以便在几秒钟后更新下一个文本视图.这意味着您将获得14层嵌套!那不是很干净的代码,对吗?

IMO, directly calling postDelayed can indeed do your job. But each postDelayed call contains another, in order to update the next text view after a few seconds. That means you'll end up with 14 layers of nesting! That's not very clean code, is it?

所以,让我介绍一下 Timer 类!

So, let me introduce the Timer class!

这里是:

import android.os.Handler;

public class Timer {
    private Handler handler;
    private boolean paused;

    private int interval;

    private Runnable task = new Runnable () {
        @Override
        public void run() {
            if (!paused) {
                runnable.run ();
                Timer.this.handler.postDelayed (this, interval);
            }
        }
    };

    private Runnable runnable;

    public int getInterval() {
        return interval;
    }

    public void setInterval(int interval) {
        this.interval = interval;
    }

    public void startTimer () {
        paused = false;
        handler.postDelayed (task, interval);
    }

    public void stopTimer () {
        paused = true;
    }

    public Timer (Runnable runnable, int interval, boolean started) {
        handler = new Handler ();
        this.runnable = runnable;
        this.interval = interval;
        if (started)
            startTimer ();
    }
}

这东西很酷.

为满足要求,让我们在活动类中添加一个 counter textViewToUpdate ,以便我们知道它的编号以及接下来要更新的文本视图.哦,将那个 textViews 变量移到类级别:

To meet the requirements, let's add a counter and textViewToUpdate to your activity class so that we know what number is it and which text view to update next. Oh, and move that textViews variable to the class level:

int counter = 1;
int textViewToUpdate = 0;

TextView[] textViews;

并在 onCreate 中初始化 textViews :

textViews = new TextView[] {
        (TextView)findViewById(R.id.player1_1),
        (TextView)findViewById(R.id.player1_2),
        (TextView)findViewById(R.id.player1_3),
        (TextView)findViewById(R.id.player1_4),
        (TextView)findViewById(R.id.player1_5),
        (TextView)findViewById(R.id.player1_6),
        (TextView)findViewById(R.id.player1_7),

        (TextView)findViewById(R.id.player2_1),
        (TextView)findViewById(R.id.player2_2),
        (TextView)findViewById(R.id.player2_3),
        (TextView)findViewById(R.id.player2_4),
        (TextView)findViewById(R.id.player2_5),
        (TextView)findViewById(R.id.player2_6),
        (TextView)findViewById(R.id.player2_7)
};

首先在您的课程中创建一个计时器:

Create a timer in your class first:

Timer t;

在您的 Initialization 方法中,创建一个可运行对象.该可运行文件将每隔几秒钟运行一次.

In your Initialization method, create a runnable. This runnable is going to be run every a few seconds.

Runnable r = new Runnable () {
    @Override
    public void run() {
        PlayActivity self = PlayActivity.this;
        self.textViews[self.textViewToUpdate].setText(Integer.toString(self.counter));
        self.textViewToUpdate++;
        if (self.textViewToUpdate == self.textViews.length) {
            self.textViewToUpdate = 0;
            self.counter++;
            if (self.counter == 8) {
                self.t.stopTimer();
            }
        }
    }
}

然后,我们创建计时器并运行它:

Then, we create the timer and run it:

t = new Timer(r, interval, true);

您可以用任何您喜欢的数字替换 interval ,也许是 250 (0.25秒)吗?

You can replace interval with any number you like, maybe 250 (0.25 seconds)?

BOOM!你做到了!

And BOOM! You did it!

这篇关于Android Studio Java更新循环中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆