Im trying to make it so that my timer adds 5 seconds every time I press the button. I've learnt that I need to cancel the previous timer and create a new one for it to work the way I want it to. When I press the button once, the timer adds 5 seconds and everything works fine as its supposed to. My problem arises when I press the button multiple times. The timer will flicker between many different timers instead of staying on the latest one. Every time I press the button, another timer is flickering on the display. Its almost as if the program doesnt cancel the previous timers and just creates a new every time. I'd really appreciate some help on this. Thanks guys!
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int scoreTeamA = 0;
String countDownTimer;
long millisUntilFinishedInt = 5000;
long milliseconds;
long seconds;
long totalAddedTime = 0;
TextView text1;
MyCount counter = new MyCount(millisUntilFinishedInt + totalAddedTime,17);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1=(TextView)findViewById(R.id.team_a_score);
counter.start();
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
millisUntilFinishedInt = millisUntilFinished;
seconds = millisUntilFinishedInt/1000;
milliseconds = millisUntilFinishedInt-(millisUntilFinishedInt/1000)*1000;
countDownTimer = "TIME: " + seconds + "." + milliseconds ;
text1.setText(countDownTimer);
}
#Override
public void onFinish() {
countDownTimer = "TIME'S UP!";
text1.setText(countDownTimer);
}
}
public void timerCreation (){
counter.cancel();
MyCount counter = new MyCount(millisUntilFinishedInt + 5000,1);
counter.start();
}
//method that is called when button is pressed
public void threePoints (View v) {
timerCreation();
}
}
Change this
public void timerCreation (){
counter.cancel();
MyCount counter = new MyCount(millisUntilFinishedInt + 5000,1);
counter.start();
}
Into this
public void timerCreation (){
counter.cancel();
counter = new MyCount(millisUntilFinishedInt + 5000,1);
counter.start();
}
With your current implementation, you are cancelling your member variable counter. Then you create a local variable with the same name and start that one. The next time you press your button, your member variable counter gets cancelled again (which is already cancelled) in order to create a new MyCount object and start that one. That is why you are ending up with multiple timers
Changes: increase interal to 50 but but mandatory.
MyCount counter = new MyCount(millisUntilFinishedInt + totalAddedTime, 50);
Align text view gravity to left android:gravity="left" so user cant feel its new timmer.
Tested Working Demo
MainActivity
public class MainActivity extends AppCompatActivity {
Context context;
int scoreTeamA = 0;
String countDownTimer;
long millisUntilFinishedInt = 5000;
long milliseconds;
long seconds;
long totalAddedTime = 0;
TextView text1;
MyCount counter = new MyCount(millisUntilFinishedInt + totalAddedTime, 50);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
text1 = (TextView) findViewById(R.id.foodName);
text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timerCreation();
}
});
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
millisUntilFinishedInt = millisUntilFinished;
seconds = millisUntilFinishedInt / 1000;
milliseconds = millisUntilFinishedInt - (millisUntilFinishedInt / 1000) * 1000;
countDownTimer = "TIME: " + seconds + "." + milliseconds;
text1.setText(countDownTimer);
}
#Override
public void onFinish() {
countDownTimer = "TIME'S UP!";
text1.setText(countDownTimer);
}
}
public void timerCreation() {
counter.cancel();
MyCount counter = new MyCount(millisUntilFinishedInt + 5000, 1);
counter.start();
}
//method that is called when button is pressed
public void threePoints(View v) {
timerCreation();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/base"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:background="#color/white"
android:orientation="horizontal"
android:weightSum="10">
<TextView
android:id="#+id/foodName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:hint="Food name"
android:gravity="left"
android:inputType="textCapWords"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#color/colorPrimaryDark"
android:textSize="32sp"
android:layout_marginLeft="20dp" />
</RelativeLayout>
Related
I am trying to make a Pomodoro Timer (25 minutes work, 5 minutes break then repeat n times). But I can't find a way to let the break timer start automatically and then start again with the work timer (work timer = 00:10 - break timer = 00:03, i put these values so i can test faster). How can I fix this?
public class MainActivity extends AppCompatActivity {
TextView tvTimer, tvSessions;
ImageView ivStart, ivStop;
SeekBar seekBar;
CountDownTimer countDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTimer = findViewById(R.id.tvTimer);
tvSessions = findViewById(R.id.tvSessions);
ivStart = findViewById(R.id.ivStart);
ivStop = findViewById(R.id.ivStop);
seekBar = findViewById(R.id.seekBar);
seekBar.setMax(2500);
seekBar.setProgress(10);
seekBar.setVisibility(View.GONE);
tvTimer.setText("00:10");
}
// ON CLICK METHODS
public void startTimer(View v){
countDownTimer = new CountDownTimer(seekBar.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
breakTimer();
}
};
countDownTimer.start();
}
public void stopTimer(View v){
}
// UPDATE METHODS
private void breakTimer(){
seekBar.setProgress(3);
tvTimer.setText("00:03");
}
private void updateTimer(int progress){
int minutes = progress / 60;
int seconds = progress - minutes * 60;
String textMinutes = String.valueOf(minutes);
String textSeconds = String.valueOf(seconds);
if(seconds < 10) textSeconds = "0" + textSeconds;
if(minutes < 10) textMinutes = "0" + textMinutes;
tvTimer.setText(textMinutes + ":" + textSeconds);
}
}
Expected output:
00:10 -> 00:00 -> 00:03 -> 00:00 -> 00:10 and so on...
What about something like this. Using a flag to keep track of if the Timer is a rest timer or a pomodoro timer.
When the timer finishes, you check the flag to decide which timer to start next (and flip the flag so next time it does the opposite).
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private static final int TICK_EVERY_SECOND = 1000;
private TextView tvTimer, tvSessions;
private ImageView ivStart, ivStop;
private SeekBar seekBar;
private CountDownTimer countDownTimer;
private boolean isRest = false;
private int userSelectedDurationSeconds = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTimer = findViewById(R.id.tvTimer);
tvSessions = findViewById(R.id.tvSessions);
ivStart = findViewById(R.id.ivStart);
ivStop = findViewById(R.id.ivStop);
seekBar = findViewById(R.id.seekBar);
seekBar.setMax(2500);
seekBar.setProgress(10);
seekBar.setVisibility(View.GONE);
tvTimer.setText("00:10");
}
// ON CLICK METHODS
public void startTimer(View v) {
isRest = false;
int durationSeconds = seekBar.getProgress();
userSelectedDurationSeconds = durationSeconds;
restartTimer(durationSeconds);
}
private void restartTimer(int durationSeconds) {
countDownTimer = new CountDownTimer(TimeUnit.SECONDS.toMillis(durationSeconds), TICK_EVERY_SECOND) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
breakTimer();
}
};
countDownTimer.start();
}
public void stopTimer(View v) {
}
// UPDATE METHODS
private void breakTimer() {
isRest = !isRest;
if(isRest) {
seekBar.setProgress(3);
tvTimer.setText("00:03");
restartTimer(3);
} else {
restartTimer(userSelectedDurationSeconds);
}
}
private void updateTimer(int progressInSeconds) {
int minutes = progressInSeconds / 60;
int seconds = progressInSeconds - minutes * 60;
String textMinutes = String.valueOf(minutes);
String textSeconds = String.valueOf(seconds);
if (seconds < 10) textSeconds = "0" + textSeconds;
if (minutes < 10) textMinutes = "0" + textMinutes;
tvTimer.setText(textMinutes + ":" + textSeconds);
}
}
I'm in the middle of a Football Match Timer project. Basically, I'm looking for an implementation of a timer which starts after pushing a "START 1st half" button, counts to 45 minutes, than pauses and we are able to start it again pushing "START 2nd half"(it would be the same button, but its text would be changed through the whole match). Then it would count from 45 minutes to 90 minutes.
I've been trying to accomplish this using Handler(), Runnable() and onClickListener(), but it doesn't work at all for me :( Would you give me some suggestions about how to tackle this?
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
showTimeRemaining();
timerHandler.postDelayed(this, 500);
}
};
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button b = (Button) v;
startButton(v);
if (b.getText().equals("Mecz trwa")) {
timerHandler.removeCallbacks(timerRunnable);
b.setEnabled(true);
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("Mecz trwa");
b.setEnabled(false);
}
}
});
public void showTimeRemaining() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView = (TextView) findViewById(R.id.time);
timerTextView.setText(String.format("%d:%02d", minutes, seconds));
}
Here are some of my suggestions.
First, encapsulate your Handler into a class called Timer. This way it's easier to manipulate your timers. Here is my version:
import android.os.Handler;
public class Timer {
private Handler handler;
private boolean paused;
private int interval;
private Runnable task = new Runnable () {
#Override
public void run() {
if (!paused) {
runnable.run ();
Timer.this.handler.postDelayed (this, interval);
}
}
};
private Runnable runnable;
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
}
public void startTimer () {
paused = false;
handler.postDelayed (task, interval);
}
public void stopTimer () {
paused = true;
}
public Timer (Runnable runnable, int interval, boolean started) {
handler = new Handler ();
this.runnable = runnable;
this.interval = interval;
if (started)
startTimer ();
}
}
Secondly, don't use System.currenTimeMillis. Use something more manipulatable. Create a variable of your own that stores how many seconds are left:
private int secondsLeft = 60 * 45;
You decrement this variable every second, until it reaches zero. Then, you stop the timer, change the button's text or whatever. This logic should be put into the Runnable used for the handler.
I would suggest to try using of CountDownTimer.
Refer here for documentation and usage:
https://developer.android.com/reference/android/os/CountDownTimer.html
I'm writing a calculator app for android using android studio. I want to used 4 buttons for inputting values and functions. However the way I am currently doing it takes the input from the text written on the button. So for my button 1/2/3 when this is pressed 1/2/3 is passed to the textView.
Below is my MainActivity:
package com.example.myfirstapp;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MediaController;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private int[] operatorButtons = {R.id.operators};
private int[] numericButtons = {R.id.onetwothree, R.id.fourfivesix, R.id.seveneightninezero};
private boolean lastNumeric, stateError;
private TextView txtScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
setOperatorOnClickListener();
}
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
// Equal button
/*findViewById(R.id.btnEqual).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqual();
}
});*/
}
}
and my activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtScreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="right|center_vertical"
android:maxLength="16"
android:padding="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30sp"
android:typeface="serif" />
<!--<Button-->
<!--android:id="#+id/equal1"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="100dp"-->
<!--android:text="="-->
<!--/>-->
<Button
android:id="#+id/equal2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="="
android:layout_alignParentBottom="true"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/txtScreen"
android:orientation="vertical"
android:layout_above="#id/equal2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="#+id/onetwothree"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="1/2/3"/>
<Button
android:id="#+id/fourfivesix"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="4/5/6"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="#+id/seveneightninezero"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="7/8/9/0"/>
<Button
android:id="#+id/operators"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="+-*/"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Will it be possible for me to get the input of 1, 2 or 3 from my first button for example? So on 1 press you get 1, 2 press gives 2 etc.
Any suggestions/ ideas on how I can move forward with this are greatly appreciated.
Kind Regards,
Ben
You could use a timer or delay variable to detect single, double or triple taps. This post may be of interest. If the time interval is not a factor, you could just keep track of the last pressed button and if the same button is being pressed again, update the text accordingly.
If you follow approach one, the code for the click listener for button onetwothree may be something like this (I commented out setNumericOnClickListener() and setOperatorOnClickListener(); in mainActivity onCreate and added the following):
Button onetwothree = (Button) findViewById(R.id.onetwothree);
onetwothree.setOnTouchListener(new View.OnTouchListener() {
Handler handler = new Handler();
int numberOfTaps = 0;
long lastTapTimeMs = 0;
long touchDownMs = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchDownMs = System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacksAndMessages(null);
if ((System.currentTimeMillis() - touchDownMs) > ViewConfiguration.getTapTimeout()) {
//it was not a tap
numberOfTaps = 0;
lastTapTimeMs = 0;
break;
}
if (numberOfTaps > 0
&& (System.currentTimeMillis() - lastTapTimeMs) < ViewConfiguration.getDoubleTapTimeout()) {
numberOfTaps += 1;
} else {
numberOfTaps = 1;
}
lastTapTimeMs = System.currentTimeMillis();
if (numberOfTaps == 1) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("1");
} else txtScreen.append("1");
}
}, ViewConfiguration.getDoubleTapTimeout());
}else if (numberOfTaps == 2) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("2");
} else txtScreen.append("2");
}
}, ViewConfiguration.getDoubleTapTimeout());
} else if (numberOfTaps == 3) {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("3");
} else txtScreen.append("3");
}
}
return true;
}
});
Complete MainActivity:
package com.example.myfirstapp;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private int[] operatorButtons = {R.id.operators};
private int[] numericButtons = {R.id.onetwothree, R.id.fourfivesix, R.id.seveneightninezero};
private boolean lastNumeric, stateError;
private TextView txtScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
// setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
// setOperatorOnClickListener();
Button onetwothree = (Button) findViewById(R.id.onetwothree);
onetwothree.setOnTouchListener(new View.OnTouchListener() {
Handler handler = new Handler();
int numberOfTaps = 0;
long lastTapTimeMs = 0;
long touchDownMs = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchDownMs = System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacksAndMessages(null);
if ((System.currentTimeMillis() - touchDownMs) > ViewConfiguration.getTapTimeout()) {
//it was not a tap
numberOfTaps = 0;
lastTapTimeMs = 0;
break;
}
if (numberOfTaps > 0
&& (System.currentTimeMillis() - lastTapTimeMs) < ViewConfiguration.getDoubleTapTimeout()) {
numberOfTaps += 1;
} else {
numberOfTaps = 1;
}
lastTapTimeMs = System.currentTimeMillis();
if (numberOfTaps == 1) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("1");
} else txtScreen.append("1");
}
}, ViewConfiguration.getDoubleTapTimeout());
}else if (numberOfTaps == 2) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("2");
} else txtScreen.append("2");
}
}, ViewConfiguration.getDoubleTapTimeout());
} else if (numberOfTaps == 3) {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("3");
} else txtScreen.append("3");
}
}
return false;
}
});
}
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
}
}
You can take all numbers when doing some operation
(Button) plusBtn = (Button) findViewById(R.id.plusBtn);
plusBtn.setOnClickListener(new OnClickListener(){
#Override
public voidonClick(View v){
number1 = Integer.parseInt(txtScreen.getText().toString());
});
Where number1 is global int. But I don't know how it can help you and if it is a good approach. You could find a better solution, just remember how to parse the String from your TextView to Integer for your calculation.
I'm developing a little app, the idea is that the user clicks a buton in 15 seconds, there's textview which counts how many clicks he does. Now I want to add a restart button, but I want to show it after 15 seconds. Do you guys have any idea how to do that? Here's my code:
final TextView textic = (TextView) findViewById(R.id.textView2);
Typeface fac=Typeface.createFromAsset(getAssets(),"fonts/fipps.otf");
textic.setTypeface(fac);
final int oldscore = getSharedPreferences("myPrefs", MODE_PRIVATE).getInt("highscore", 0);
count = new CountDownTimer(15000, 1000) { // MOVED UP
public void onTick(long millisUntilFinished) {
int seconds = (int) ((millisUntilFinished / 1000));
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
String message;
textic.setText("Time's Up!");
buttonCount.setEnabled(false);
if (clicks > oldscore) {
getSharedPreferences("myPrefs", MODE_PRIVATE).edit().putInt("highscore", clicks).commit();
}
}
};
final TextView textView = (TextView) findViewById(R.id.clicks);
Typeface face=Typeface.createFromAsset(getAssets(),"fonts/fipps.otf");
textView.setTypeface(face);
buttonCount = (ImageButton) findViewById(R.id.button);
buttonCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
clicks++;
textView.setText("" + clicks);
TextView textVie = (TextView) findViewById(R.id.topScoreView);
Typeface fa=Typeface.createFromAsset(getAssets(),"fonts/fipps.otf");
textVie.setTypeface(fa);
textVie.setText("Best: " + oldscore);
if(!started){
count.start(); // START COUNTDOWN TIMER
started = true;
timerProcessing = true;
}
}
});
}
}
Could someone please help me, what should I do?
just add the button in your layout like your textview and set it unvisible.Set it visible when time's out(in onfinish()).
This is my code. I used this to hide a layout after 5 seconds,, use this. Hope this will help u
private void HideLayout()
{
swiper=(RelativeLayout)findViewById(R.id.llSwiper);
header=(LinearLayout)findViewById(R.id.llHeader);
swiper.postDelayed(new Runnable()
{
public void run()
{
if(!swiper.isPressed())
{
swiper.setVisibility(View.GONE);
}
else
{
HideLayout();
}
}
}, 5000);
}
I'm trying to make a countdown timer starting at 10 minutes, similair to a basketball scoreboard: 10:00 to 00:00. How would I do that? This is my code:
private TextView Timer;
Handler handler = new Handler();
private int length = 120000;
private int decision = 0;
MyCount counter;
public String formatTime(long millis) {
String output = "00:00";
long seconds = millis / 1000;
long minutes = seconds / 60;
seconds = seconds % 60;
minutes = minutes % 60;
String sec = String.valueOf(seconds);
String min = String.valueOf(minutes);
if (seconds < 10)
sec = "0" + seconds;
if (minutes < 10)
min= "0" + minutes;
output = min + " : " + sec;
return output;
}//formatTime
#Override
public void onCreate(Bundle cute) {
super.onCreate(cute);
counter = new MyCount(length, 1000);
updateTime();
handler.removeCallbacks(updateTimeTask);
handler.postDelayed(updateTimeTask, 1000);
}//end of cuteness
private Runnable updateTimeTask = new Runnable() {
public void run() {
updateTime();
handler.postDelayed(this, 1000);
}
};
private void updateTime() {
switch (decision) {
case 0:
startTime = 0L;
counter.start();
decision=1;
break;
case 1:
counter.onPause();
decision=0;
break;
}
}//updateTime
class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}//MyCount
public void onPause() {
//do stuff later
onPause();
}//finish
public void onTick(long millisUntilFinished) {
Timer.setText("" + formatTime(millisUntilFinished));
}//on tick
#Override
public void onFinish() {
onStop();
}//finish
}//class MyCount
Any help would be appreciated. thanks!
This does not have to be too hard. You've already created your functionality for writing your time in letters, now you need to count down. Starting a timer is easy, just do this in your start button event handler (or whatever you choose to use) (modified example from the android developer reference:
// New timer for 10 minutes, starts after initialization
new MyCount(600000, 1000)
{
// Updates the text on your "scoreboard" every second
public void onTick(long millisUntilFinished)
{
Timer.setText("Time remaining: " + formatTime(millisUntilFinished));
}
public void onFinish()
{
mTextField.setText("done!");
}
}.start();
And that's all you need! You can skip your UpdateTime function and your updateTimeTask. Just replace all this on your onCreate method
counter = new MyCount(length, 1000);
updateTime();
handler.removeCallbacks(updateTimeTask);
handler.postDelayed(updateTimeTask, 1000);
With my code. Or modify it as you please!
why don't you just create 3 textviews so that it will be easier for you to code?
one for the minutes.
one for the colon.
one for the seconds.
then use the code he's using.
hope I helped.
The way i think of making a count down is just saving at the beginning the (current time + 10 minutes) aside and then just subtract it from current time every second in your handler and display the result in the desired format..