gpt4 book ai didi

java - 如何从使用可运行接口(interface)的类更新 UI 上的 TextView?

转载 作者:行者123 更新时间:2023-12-02 12:57:42 25 4
gpt4 key购买 nike

public class Stopper implements  Runnable {

private long mStartTime;
private volatile int since;
private Handler handler;
private TextView tv;
private Activity activity;
private Context context;


/*
* Constants
* */
public static final int MILISEC_TO_MINUTE = 60000;
public static final int MILISEC_TO_HOUR = 3600000;

/*
* Flags
* */
private boolean mIsRunning;

public Stopper(){
//this.context = context;
activity = (Activity)context;
Message message = Message.obtain();
handler = new Handler(Looper.getMainLooper());

}
public void start(){
mStartTime = System.currentTimeMillis();
mIsRunning = true;


}
public void stop(){
mIsRunning = false;
}

@Override
public void run () {
while (mIsRunning) {
since = (int)(System.currentTimeMillis() - mStartTime);
int hours = (since / MILISEC_TO_HOUR) % 24; // ms -> h; 360 000= 1[h]
int minutes = (since / MILISEC_TO_MINUTE) % 60;// ms -> min; 60 000[ms] = 1[min]
int seconds = (since / 1000) % 60; // ms -> s ;1 000[ms] = 1[s] -> (1000 [ms] /1000)%60 = 1[s]
int ms = since % 1000;


tv.setText(String.format("%02d:%02d:%02d:%03d", hours, minutes, seconds, ms));


//((Activity) context).updateTimerText(String.format("%02d:%02d:%02d:%03d", hours, minutes, seconds, ms));
}
}
public void getStooperTextView(TextView textView)
{
this.tv = textView;
}

public int getSince() {
return since;
}
}

我读了一些关于 chronometer 的教程。它工作得很好,直到我开始需要在两个不同的 Activity 中使用计时器。下面这行代码需要返回值。

((Activity) context).updateTimerText(String.format("%02d:%02d:%02d:%03d", hours, minutes, seconds, ms));

因此,我尝试使用 Handler 类,但要做到这一点,我需要一个可运行的对象。

最佳答案

我相信这个方法Activity#runOnUiThread就是你所需要的

关于java - 如何从使用可运行接口(interface)的类更新 UI 上的 TextView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44373633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com