Reputation: 193
I want to make a simple timer that will when I click button
starts timing and when I click second time on the button I get elapsed time in milliseconds to 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));
}
}
});
}
I get value of 0 when I launch app
Upvotes: 1
Views: 234
Reputation: 827
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();
}
});
}
Upvotes: 1
Reputation: 4328
Try this
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++;
}
}
});
Upvotes: 0
Reputation: 569
You save the start
each time you click the button, so start
and end
should be almost the same.
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;
}
}
});
Upvotes: 0