gpt4 book ai didi

android - StartTimer() 应该在按钮单击事件完成后调用,但它在 onclick 事件之前执行

转载 作者:行者123 更新时间:2023-12-02 06:17:28 27 4
gpt4 key购买 nike

StartTimer() 函数应该在按钮单击事件完成后调用,但它在 onclick 事件之前执行。如何在 onclick 事件之前停止计时器并在 onclick 事件之后启动计时器。

我该如何解决这个问题?

        btn1=(Button)findViewById(R.id.button);
btn2=(Button)findViewById(R.id.button2);
btn3=(Button)findViewById(R.id.button3);
timer = new Timer();

btn1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
timer.cancel();
Toast.makeText(getApplicationContext(), "Button1", Toast.LENGTH_SHORT).show();
}
});
StartTimer();

btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timer.cancel();
Toast.makeText(getApplicationContext(), "Button2", Toast.LENGTH_SHORT).show();
}
});
StartTimer();

btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timer.cancel();
Toast.makeText(getApplicationContext(), "Button3", Toast.LENGTH_SHORT).show();
}
});
}

public void StartTimer()
{
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Log.v("timer", "Timer running");
}
}, 0, 5000);

Toast.makeText(getApplicationContext(), "Timer", Toast.LENGTH_LONG).show();
}

protected void onResume() {
super.onResume();
StartTimer();
}
}

最佳答案

android 中已经内置了 Timer 类。所以你可以这样做:

    import java.util.Timer;

Timer timer = new Timer();

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

timer.schedule(new TimerTask() {
@Override
public void run() {
Log.v("timer", "Timer running");
Toast.makeText(getApplicationContext(), "TIMER HAS FINISHED", Toast.LENGTH_SHORT).show();
}
}, 0, 5000);

btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timer.cancel();
Toast.makeText(getApplicationContext(), "Button1", Toast.LENGTH_SHORT).show();
}
});

StartTimer();

btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timer.cancel();
Toast.makeText(getApplicationContext(), "Button2", Toast.LENGTH_SHORT).show();
}
});

btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timer.cancel();
Toast.makeText(getApplicationContext(), "Button3", Toast.LENGTH_SHORT).show();
}
});

因此,只需在 onCreate 中启动计时器,并在单击按钮时停止它。

关于android - StartTimer() 应该在按钮单击事件完成后调用,但它在 onclick 事件之前执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38541940/

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