首页 > 解决方案 > 从另一个类中获取 TextView 进行倒计时

问题描述

我创建了一个类来进行倒计时,并用它来将格式化的时间作为 TextView 返回。但是,我无法获得时间到位。当我使用字符串而不是调用 getTime() 方法时,它显示得很好。

主要方法是这样的:

setContentView(R.layout.activity_main);

matchTime = findViewById(R.id.match_Time);

playTime = new Play();
matchTime.setText(playTime.getPlayTime());

虽然我的课堂游戏是这样的:

//Other implementations

    private void updatePlay() {
          int minutes = (int) (timeUntilEnd/ 1000) / 60;
          int seconds = (int) (timeUntilEnd/ 1000) % 60;

         timeUntilEndFormated= String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
         playTime.setText(timeUntilEndFormated);
    }

    public TextView getPlayTime() {
        return playTime;
    }


标签: javaandroidtextview

解决方案


看起来您正在将 matchTime 的文本设置为 TextView。setText 是一种应该接收字符串而不是 TextView 对象的方法。

但是,如果您只是在 getPlayTime() 中返回一个字符串,那么 updatePlay() 将不起作用,因为 playTime.setText() 根本不会影响 matchTime。

为了解决这个问题,你将 matchTime 传递给 Play 的构造函数,然后直接更新它:

public class Play{
    
    private TextView matchTime;

    public Play(TextView matchTime){
        this.matchTime = matchTime;
    }

     private void updatePlay() {
       int minutes = (int) (timeUntilEnd/ 1000) / 60;
       int seconds = (int) (timeUntilEnd/ 1000) % 60;

       timeUntilEndFormated= String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
       matchTime.setText(timeUntilEndFormated);
     }
}

然后你只需要在你的 main 方法中这样做:

playTime = new Play(matchTime);
playTime.updatePlay();

小心将 TextView 传递给其他对象。这可能会造成内存泄漏,因为 TextView 拥有 Context 的一个实例。为避免内存泄漏,您必须在 Activity 的 onDestroy() 方法中释放对象:

 public void onDestroy() {
    super.onDestroy();
    playTime = null;
 }

推荐阅读