我的android活动中有一个文本视图,我想将它传递给另一个java类中的函数并修改其文本。但它给我一个例外。我读到我需要在UI线程上运行它或发送到上下文变量,但我有点困惑,我无法做到这一点。那是我的代码:
Java计时器类
public class CountdownTimer {
static int duration;
static Timer timer;
public static void startTimer(final TextView TVtime) {
duration = 10;
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
TVtime.setText(setDuration());
}
}, 1000, 1000);
}
private static String setDuration(){
if(duration == 1)
timer.cancel();
return String.valueOf(--duration);
}
}
Android活动:
TVtime = (TextView) findViewById(R.id.textView_displayTime);
CountdownTimer.startTimer(TVtime);
答案 0 :(得分:2)
您无法从非UI线程更新UI。将activity
Context
传递给startTimer()
方法。
public static void startTimer(final TextView TVtime,final Context activityContext) {
duration = 10;
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
((Activity) activityContext).runOnUiThread(new Runnable() {
public void run()
{
TVtime.setText(setDuration());
}
});
..........................
.......................
Android活动:
TVtime = (TextView) findViewById(R.id.textView_displayTime);
CountdownTimer.startTimer(TVtime, YourActivity.this);
答案 1 :(得分:1)
您可以使用android.os.Handler:
public static void startTimer(final TextView TVtime) {
duration = 10;
final Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
TVtime.setText((String) msg.obj);
}
};
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Message msg = new Message();
msg.obj = setDuration();
handler.sendMessage(msg);
}
}, 1000, 1000);
}