Start timer on button click - android

I'm new in Android programming but i know Java.
My question is, how does a timer work in Android? I've read that is better to use a handler.
What I want to do is, you click a button and the timer starts. To the moment when the button is clicked all is clear for me but how to start the timer?

How does a timer work in Android?
You better read Timer documentation, CountDownTimer Documentation and Handler Documentation.
To the moment, when the button is clicked, all is cleared for me; but, how can I start the timer?
If I didn't misunderstand your question, when you say Timer, you refer to CounteDownTimer. So, you should have something like this:
(I've written a sample code. So, you should understand it first, and then, you should apply it to your code.)
Adding the Buttons
btn1 = (Button)findViewById(R.id.bt1);
btn2 = (Button)findViewById(R.id.bt2);
Adding the SetOnClickListener()
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
});
}
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
});
}
My btn1 starts the CountDownTimer, and the second one stops and clears it.
Now, I create an Inner Class with CountDownTimerTest name.
public class CountDownTimerTest extends CountDownTimer {
public CountDownTimerTest(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
text.setText("Time's up!");
timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("Time remain:" + millisUntilFinished);
timeElapsed = startTime - millisUntilFinished;
timeElapsedView.setText("Time Elapsed: " + String.valueOf(timeElapsed));
}
}
Then on my btn1, I put this code (start the CountDownTimer):
countDownTimer.start();
And on my btn2, I put this code (stop/cancel the CountDownTimer):
countDownTimer.cancel();
Now, I hope that you can understand how CountDownTimer works, if your question isn't about CountDownTimer, let me know, and I'll update my answer as soon as possible with your wishes.
EDIT - Only with one Button
To do it with the same Button, you can do this:
Create a Boolean variable as:
Boolean ButtonClicked = false;
And then, modify the code as follows:
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!ButtonClicked)) {
ButtonClicked = true;
countDownTimer.start();
} else {
ButtonClicked = false;
countDownTimer.cancel();
}
});
}
EDIT 2 Get what button is clicked
You can create an int called NumberButtonClicked like this :
int NumberButtonClicked = 0;
Then on every Button you have you'll have to do this (Example) :
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
NumberButtonClicked = 1;
});
}
Then you know that if you have clicked btn1 your variable will be 1.

Related

How to pause the countdown timer if activity dialog appeared

How can I pause the countdownTimer if a dialog need to appear first. What can I do so that the timer will not start until I click the ok button.
countDownTimer = new CountDownTimer(320000, 1200) {
#Override
public void onTick(long l) {
timeText.setText(String.valueOf(timeValue));
timeValue = timeValue - 1;
if (timeValue == -1){
FLAG = 3;
playAudio.setAudioforEvent(FLAG);
timerDialog.timerDialog();
countDownTimer.cancel();
dbHandler.addScore2(tag,Integer.parseInt(txtCorrect.getText().toString()));
}
}
#Override
public void onFinish() {
// timerDialog.timerDialog();
}
}.start();
This is the dialog that will appear first.
public void fillDialog(){
fillDialog = new Dialog(mnContext);
fillDialog.setContentView(R.layout.activity_instruction_fill);
final Button btdialog = (Button) fillDialog.findViewById(R.id.ok_btn_fill);
btdialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fillDialog.dismiss();
}
});
You can use the countdownTimer.cancel() method to pause the countdown timer. When the dialog appears, call this method to pause the timer. When the user clicks the "OK" button on the dialog, you can then call the countdownTimer.start() method to resume the timer from where it left off.
Alternatively, you can also use countdownTimer.pause() and countdownTimer.resume() to pause and resume the timer.
It would be good to keep in mind that countdownTimer is a android class and you need to call the above methods from your activity class

How to disable button for 1 sec after clicked in Android?

I am using following code for using a button. I works.(sendBtn is a button in a fragment)
sendText = view.findViewById(R.id.send_text);
View sendBtn = view.findViewById(R.id.send_btn);
sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
Now i want to disable the button for 1 sec after a click
I found following solution but above code works "without onClick(View v)"method and without implementing View.OnClickListener in class. How to provide delay in such case..How code is working without onClick method.
#Override
public void onClick(View v) {
((Button) findViewById(R.id.click)).setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
((Button) findViewById(R.id.click))
.setEnabled(true);
}
}, 1000);
}
});
Use this method when you want to interrupt user clicks:
private static long mLastClickTime = 0L;
public static boolean isOpenRecently() {
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
return true;
}
mLastClickTime = SystemClock.elapsedRealtime();
return false;
}
Usage:
if (v.getId() == R.id.sendBtn) {
if (isOpenRecently()) return;
// Your logic
}
Basically you are using lambda in your code, where v->{} represents the onCLick(View v) function.
sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
You can do the following to disable the button for 1 second
void doOnSendButtonClick(View v){
//Send the message (your logic here)
send(sendText.getText().toString());
//Disable button
sendBtn.setEnabled(false);
//enable button after 1000 millisecond
new Handler(Looper.getMainLooper()).postDelayed(() -> {
sendBtn.setEnabled(true);
}, 1000);
}
And call this method when user clicks on the button
sendButton.setOnClickListener(view -> doOnSendButtonClick(view));
You could use a CountDownTimer.
CountDownTimewr timer = new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
// enable button
((Button) findViewById(R.id.click)).setEnabled(true);
}
}
#Override
public void onClick(View v) {
// disable btn and start timer of one second in millis
((Button) findViewById(R.id.click)).setEnabled(false);
timer.start();
}
});
Please try this way
Handler(Looper.getmainLooper()) and remove callback after you done your task inside runnable thread...also try to put this logic in any method outside in this class and call from setonclicklistener
Try the Timer.shedule with timertask
you can use runOnUIThread method inside where you can update UI.
you can also try to check the time difference of click and enable again in looping like while.

Countdown timer that that increases speed after button press

I am trying to create a countdown timer that will increases its speed after a button press I uses the counter also to adjust a progress bar.
Right now I am adjusting the speed (increasing) after the button is pressed but it does not start from the beginning. For example, when I start my program the timer start from the beginning and decreases progressively, which is fine. However, when I press the button the counter does not start from the beginning like this:
I want just to make it run faster after each button press, not to decrease the length.
this is my code:
mTrueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//is the user right? if pressing True button
if(isMathProblemTrue == 1){
//user is correct
Toast.makeText(MainActivity.this,"Correct!",Toast.LENGTH_SHORT).show();
generateMathProblem();
timer_length *= 0.8;
timer_interval *= 0.8;
Log.d(TAG,"time length:"+timer_length);
Log.d(TAG,"time interval:"+timer_interval);
mCountDownTimer.cancel();
createNStartTimer();
//restartTimer();
}else{
//user is incorrect
transferUserToStartScreen();
//reset the timer
mCountDownTimer.cancel(); // cancel
}
}
});
private void createNStartTimer() {
mCountDownTimer = new CountDownTimer(timer_length,timer_interval) {
#Override
public void onTick(long millisUntilFinished) {
Log.d(TAG,"Mil until finish:"+millisUntilFinished);
int progress = (int) (millisUntilFinished/100);
mProgressBar.setProgress(progress);
}
#Override
public void onFinish() {
mProgressBar.setProgress(0);
transferUserToStartScreen();
}
}.start();
}
create 2 global constants outside the functions
int totalMillisUntilFinished = 0;
bool firstTime = true;
we initialize the totalMillisUntilFinished when onTick is called for the time, so update your your onTick function:
private void createNStartTimer() {
firstTime = true;
mCountDownTimer = new CountDownTimer(timer_length,timer_interval) {
#Override
public void onTick(long millisUntilFinished) {
if(firstTime){totalMillisUntilFinished = millisUntilFinished; firstTime = false;}
Log.d(TAG,"Mil until finish:"+millisUntilFinished);
int progress = (int) (millisUntilFinished*100/totalMillisUntilFinished);
mProgressBar.setProgress(progress);
}
Personally, I use Handlers and Runnables, which I would definitely suggest looking into instead.

Trigger a Miss count when button is not click android

I'm creating a simple whack a mole game using buttons,so far I only managed to get the score of the game when the button is clicked into the count.How do I register a miss count when button is not pressed?
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b1 = (Button)findViewById(R.id.button1);
b2 = (Button)findViewById(R.id.button2);
final Handler handler = new Handler();
Runnable runnable = new Runnable() { public void run() {
int x1= r1.nextInt(array.length);
int x2= r2.nextInt(array.length);
b1.setText(array[x1].toString());
b1.setText(array[x1].toString());
int rando = (int)((Math.random()) * 2000);
handler.postDelayed(this, rando); //for interval...
}
};
handler.postDelayed(runnable, 2000);
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(b1)){
//Toast.makeText(Random_textviewActivity.this, "Hello", Toast.LENGTH_SHORT).show();
count++;
score.setText(String.valueOf(count));
b1.setText("");
}
else if (v.equals(b2)) {
count++;
score.setText(String.valueOf(count));
b2.setText("");
}
Those are part of my codes,is there any way to register a count for button not being clicked?
UPDATE
Okay I've got a grasp of the whole idea now,but due to I'm still not very good with android programming yet,I've gotten a lot of error while trying to do what you thought me.Belows are part of the code I've gotten so far:
b1 = (whackamolebutton) findViewById(R.id.button1);
((whackamolebutton) b1).setmoleactive(this);
public class whackamolebutton extends Button{
public whackamolebutton(Context context) {
super(context);
// TODO Auto-generated constructor stub
}//it insist I must cast a method here which I'm not sure why
//from this point onwards I got confused by the auto fix from eclipse.
public void setmoleactive(Random_textviewActivity random_textviewActivity){
if (boolean active){
count++
}
else{
misscount++
}
}
public int getScore(){
return count;
}
}
Any help with the code would be greatly appreciated.Thank you in advance.
I would prefer implementing a custom Button:
public class WhackAMoleButton extends Button {
public void setMoleActive(boolean active) {
...
}
public int getScore() {
...
}
}
The idea is to collect the total score/count from all visible "WhackAMoleButton"s and move the count logic into the WhackAMoleButton-Class. If the button changes from moleActive(true) to moleActive(false) and there was no click in the meantime, you could raise the "not being clicked"-count.

Countdown Timer keeps starting over on button press

Okay, so I have a countdown timer, and my app requires the user to tap a button numerous times, however the timer starts ON that button tap. My problem is:
I have a 10 second countdown timer that starts at the press of the button, but instead of just continuing down to 0, it restarts at 10 everytime the user taps the button. How do I make it so when the user taps it the first time, it keeps counting down?
My code:
private Button tapBtn;
TextView cm;
tapBtn = (Button) findViewById(R.id.Tap);
cm = (TextView) findViewById(R.id.Timer);
final CountDownTimer aCounter = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
cm.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
cm.setText("Time's Up!");
}
};
aCounter.cancel();
tapBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scr = scr - 1;
TextView Score = (TextView) findViewById(R.id.Score);
Score.setText(String.valueOf(scr));
aCounter.start();
}
});
}
Are you trying to make it so that if the user has already started the timer, subsequent button presses don't restart it from the first tap? If so, all you should have to do is put an if statement in your onclick that checks to see if the timer is still counting down, i.e. check and see if the current time is greater than 0 on the counter.
Edit: here's code
final CountDownTimer aCounter = new CountDownTimer(10000, 1000) {
private long timeLeft;
public long getTimeLeft() {
return timeLeft;
}
public void onTick(long millisUntilFinished) {
timeLeft = millisUntilFinished / 1000;
cm.setText("Time Left: " + timeLeft);
}
public void onFinish() {
cm.setText("Time's Up!");
}
};
aCounter.cancel();
tapBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (aCounter.getTimeLeft() == 0) {
scr = scr - 1;
TextView Score = (TextView) findViewById(R.id.Score);
Score.setText(String.valueOf(scr));
aCounter.start();
}
}
});
}
one way to do it is to create a flag that gets set on the first tap and have the onclick event flip the flag on the first click, and put the timer start inside of an if statement that only occurs if the flag hasn't been set.

Categories

Resources