java - 从另一个类中获取 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() 中返回一个字符串,那么 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;
}
推荐阅读
- python - Python:无法将 wav 转换为 flac
- python - Python:使用 tkinter 递增类属性
- android - 如何发送对新活动的响应?
- java -
我遇到了 Primefaces 的 selectMany 组件的问题。
我检查了 selectManyMenu 中的一些选项,但在 bean bReservarPista 中返回了 arrayList 大小 0
<p:selectManyMenu id="manyHoras" value="#{
- python - 如何检查用户的输入是否有效 Python
- vb.net - 如何在 Visual Studio 2015 中对 Crystal Report 进行排序
- kubernetes - Google Kubernetes Engine 上的 Traefik 错误
- java - Eclipse Gradle 项目中突然丢失依赖项
- linux - 尝试运行 make 命令时出错
- firebase - Firebase:阅读孩子后的行动