gpt4 book ai didi

java - Timer多次添加某个TableRow

转载 作者:行者123 更新时间:2023-11-30 00:43:48 24 4
gpt4 key购买 nike

我的应用中有一个基本的计时器:

TextView timerTextView = (TextView) findViewById(R.id.timer);
long startTime = 0;

Handler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000) * 1;
int minutes = seconds / 60;
seconds = seconds % 60;

timerTextView.setText(String.format("%02d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);

if (minutes == 45 && seconds == 0) {
addHeader("2nd Half");
}
}
};

addHeader() 方法:

private void addHeader(String header) {
TableLayout table = (TableLayout) findViewById(R.id.myTable);
TableRow tr = new TableRow(this);
tr.setLayoutParams(...);

TextView textView = new TextView(this);
textView.setLayoutParams(..);
textView.setText(header);

// more code

tr.addView(textView);
table.addView(tr);
}

onCreate():

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

startTimer();
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
}

当我的计时器到达 45:00 时,新行会多次添加到我的 TableLayout 中。我已经创建了一个替代解决方案,但我想知道我遗漏了什么。

if (!isAdded) {
addHeader("2nd Half");
isAdded = true;
}

最佳答案

检查正在发生的事情的一个好方法是在每次运行 Handler 和每次 addHeader 触发时记录

例如:

    Runnable timerRunnable = new Runnable() {

@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000) * 1;
int minutes = seconds / 60;
seconds = seconds % 60;
millis = millis % 1000;

timerTextView.setText(String.format("%02d:%02d", minutes, seconds));
Log.d("MainActivity", String.format(Locale.ENGLISH,"Checking time: %02d:%02d:%03d" , minutes, seconds, millis));
timerHandler.postDelayed(this, 500);

if (minutes == 45 && seconds == 0) {
Log.d("MainActivity", String.format(Locale.ENGLISH,"2nd Half: %02d:%02d:%03d" , minutes, seconds, millis));
addHeader("2nd Half");
}
}

这样做你会看到 addHeader 被调用了两次。这是因为每 500ms 您的 Handler 都会运行,检查当前时间和开始时间之间的差异,以分钟和秒为单位(忽略毫秒)。要解决此问题,请尝试更改

timerHandler.postDelayed(this, 500);

timerHandler.postDelayed(this, 1000);

关于java - Timer多次添加某个TableRow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42123644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com