如何在一个时间限制内记录点击次数 [英] How to record number of clicks within a time limit
问题描述
我尝试制作一个应用程序,用户可以在20秒内点击一个按钮,并在结束时记录和显示总点击次数
程序既不会终止也不会执行
我尝试过:
私人TextView t1;
private Button btn;
private int count = 0;
private long startTime = System.currentTimeMillis();
private long endTime = System.currentTimeMillis()+ 20000;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 =(TextView)findViewById( R.id.textView);
btn =(Button)findViewById(R.id.button);
while(startTime<结束时间)
{
btn.setOnClickListen呃(新的View.OnClickListener()
{
@Override
public void onClick(查看视图)
{
count = count + 1;
}
});
}
t1.setText(Integer.toString(count));
}
I tried making an app where the user gets 20 seconds to click a button and at the end of the time the total number of clicks are recorded and displayed
The program is neither terminating nor executing
What I have tried:
private TextView t1;
private Button btn;
private int count = 0;
private long startTime = System.currentTimeMillis();
private long endTime = System.currentTimeMillis()+20000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (TextView)findViewById(R.id.textView);
btn = (Button)findViewById(R.id.button);
while(startTime < endTime)
{
btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
count = count + 1;
}
});
}
t1.setText(Integer.toString(count));
}
推荐答案
while (startTime < endTime)
第一个问题:你要比较两个固定值,它们被初始化一次然后永远不会改变。
您将要用 System.currentTimeMillis()
替换 startTime
。
First problem: you're comparing two fixed values, which are initialized once and then never change.
You're going to want to replace startTime
with System.currentTimeMillis()
.
btn.setOnClickListener(new View.OnClickListener() ...
第二个问题:你'永远不要求代码终止。而是在一个紧凑的循环中一遍又一遍地添加一个新的点击处理程序。
一个简单的解决方案是添加处理程序一次,并检查 onClick
方法中的时间限制:
Second problem: you're never asking the code to terminate. Instead, you're adding a new "click" handler over and over again in a tight loop.
A simple solution would be to add the handler once, and check the time limit within the onClick
method:
private TextView t1;
private Button btn;
private int count = 0;
private long endTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
endTime = System.currentTimeMillis() + 20000;
t1 = (TextView)findViewById(R.id.textView);
btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (System.currentTimeMillis() < endTime) {
count = count + 1;
t1.setText(Integer.toString(count));
}
}
});
}
这篇关于如何在一个时间限制内记录点击次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!