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

查看:35
本文介绍了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.

因此,当我从主要活动中按下按钮时,它会运行一个名为 play 的活动.它有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.

但是在运行下面的代码之后,它只是在片刻之后显示了十四个 7.(也不能以 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 线程休眠.

你需要一些可以在一段时间后做一些工作的东西.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 ();
    }
}

这东西很酷.

为了满足要求,让我们添加一个 countertextViewToUpdate 到您的活动类,以便我们知道它是什么数字以及接下来要更新哪个文本视图.哦,将 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 方法中,创建一个 runnable.这个 runnable 将每隔几秒运行一次.

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)?

然后轰隆隆!你做到了!

And BOOM! You did it!

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

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