从另一个 class 获取 TextView 进行倒计时

Get TextView from another class for countdown

我创建了一个 class 来进行倒计时,并将其用于 return 作为 TextView 的格式化时间。但是,我无法抽出时间进行现场表演。当我使用字符串而不是调用方法 getTime() 时,它显示正常。

主要方法是这样的:

setContentView(R.layout.activity_main);

matchTime = findViewById(R.id.match_Time);

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

虽然我的 class 游戏是这样的:

//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;
    }


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

但是,如果您只是 return 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);
     }
}

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

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

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

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