从另一个类获取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;
    }


解决方法

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

但是,如果仅在getPlayTime()中返回一个String,则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的实例,所以这可能会造成内存泄漏。为了避免内存泄漏,您必须在活动的onDestroy()方法中释放该对象:

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...