我想创建一个简单的计时器,当我点击button
开始计时时,当我第二次点击按钮时,我会得到经过的时间(以毫秒为单位)到textView
。
public class MainActivity extends AppCompatActivity {
int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView) findViewById(R.id.textView);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
long start = System.currentTimeMillis();
i++;
if (i >= 2)
{
long end = System.currentTimeMillis();
long diff = end - start;
textView.setText(String.valueOf(diff));
}
}
});
}
启动应用
时,我的值为0
答案 0 :(得分:1)
public class MainActivity extends AppCompatActivity {
private long start = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView) findViewById(R.id.textView);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (start > 0) {
long end = System.currentTimeMillis();
long diff = end - start;
textView.setText(String.valueOf(diff));
start = 0;
} else {
start = System.currentTimeMillis();
}
});
}
答案 1 :(得分:0)
每次点击按钮都会保存start
,因此start
和end
应该几乎相同。
final TextView textView = (TextView) findViewById(R.id.textView);
Button button = (Button) findViewById(R.id.button);
long start = -1;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(start < 0)
start = System.currentTimeMillis();
else {
long end = System.currentTimeMillis();
long diff = end - start;
textView.setText(String.valueOf(diff));
start = -1;
}
}
});
答案 2 :(得分:0)
试试这个
int i = 1;
long start,end;
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (i == 2)
{
end = System.currentTimeMillis();
long diff = end - start;
textView.setText(String.valueOf(diff));
i = 1;
}
else
{
start = System.currentTimeMillis();
i++;
}
}
});