如何在 Android Studio 中自动增加 TextView 值

How to Autoincrement the TextView value in Android Studio

I want to Increment the TextView's value in Android Studio automatically but the problem i am facing is > when i run the following code it only show the app interface when the code is finished. Any Solution?

package com.example.assignment2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import static android.os.SystemClock.sleep;

public class MainActivity extends AppCompatActivity{
private TextView tv;
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = findViewById(R.id.t);
    while(count<10000000) {
    count++;
    tv.setText("" + count);
    }
}

}

这里的问题是:

在 Android 上,有一个叫做 Main Thread 的东西。该线程负责呈现您应用程序的所有 UI,如果该线程正忙于任何其他任务(例如 运行 有 10.000.000 个循环),您的 UI 将只冻结,因为没有可用于呈现 UI 的资源。为避免此类问题,您应该 运行 代码的重部分放在单独的线程中,并且所有 UI 更新都在主线程 / UI 线程中(两者是同一件事).进行这些更改后,您的代码将如下所示:

package com.example.assignment2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import static android.os.SystemClock.sleep;

public class MainActivity extends AppCompatActivity{
private TextView tv;
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = findViewById(R.id.t);
    //Creating a new thread
        new Thread(new Runnable() {
            @Override
            public void run() {
                //This while will run on this new thread
                while(count<10000000) {
                    count++;
                    /*To ensure that the TextView update will run on the right thread
                    * we should run this update inside the runOnUiThread method*/
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv.setText("" + count);
                        }
                    });
                }
            }
        });
}

要了解有关线程的更多信息,请查看这篇文章:

https://developer.android.com/topic/performance/threads

   new Thread(new Runnable(){
        @Override
        public void run() {
            int counter = 0;
            while (counter < 10000000) {
                counter++;
                final String counterStr = counter.toString();
                tv.post(new Runnable(){
                    @Override
                    public void run() {
                        tv.setText(counterStr);
                    }
                });
                Thread.sleep(1000);
                }
            }
        }).start();