I want to use a stop watch in my app. So I try this tutorial but what I need are two changes and I can't really figure them out.
I found a bug that when I press start and then again it will start again. So what I want is a start button that will change into a pause button when pressed and visa versa. How can I switch the buttons?
My layout for the buttons is this:
<Button
android:id=”#+id/btnPause”
android:layout_width=”90dp”
android:layout_marginLeft=”20dp”
android:layout_height=”45dp”
android:layout_centerVertical=”true”
android:layout_toRightOf=”#+id/btnStart”
android:text=”Pause” />
<Button
android:id=”#+id/btnStart”
android:layout_width=”90dp”
android:layout_height=”45dp”
android:layout_alignParentLeft=”true”
android:layout_centerVertical=”true”
android:layout_marginLeft=”68dp”
android:text=”Start” />
The class is this:
package com.androidituts.stopwatch;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class StopwatchActivity extends Activity {
/** Called when the activity is first created. */
private TextView textTimer;
private Button startButton;
private Button pauseButton;
private long startTime = 0L;
private Handler myHandler = new Handler();
long timeInMillies = 0L;
long timeSwap = 0L;
long finalTime = 0L;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textTimer = (TextView) findViewById(R.id.textTimer);
startButton = (Button) findViewById(R.id.btnStart);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
myHandler.postDelayed(updateTimerMethod, 0);
}
});
pauseButton = (Button) findViewById(R.id.btnPause);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwap += timeInMillies;
myHandler.removeCallbacks(updateTimerMethod);
}
});
}
private Runnable updateTimerMethod = new Runnable() {
public void run() {
timeInMillies = SystemClock.uptimeMillis() – startTime;
finalTime = timeSwap + timeInMillies;
int seconds = (int) (finalTime / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
int milliseconds = (int) (finalTime % 1000);
textTimer.setText(“” + minutes + “:”
+ String.format(“%02d”, seconds) + “:”
+ String.format(“%03d”, milliseconds));
myHandler.postDelayed(this, 0);
}
};
}
i did the same thing with a button that toggled everytime you pressed it. here is how i did it
declare a int state = 1
the state means the functionality and the appearance of the button that would be. lets say 1 is start 2 is pause and 3 is stop(just for the tutorial purpose).
set the default state (in this case 1) and accordingly set the background
check the state everytime in the onclicklistener if the state is 1 implement the corresponding functionality, change the button background to pause and change the state to 2, and similarly for the rest of the others
Good Luck
you can change text of button yourself, or you should try Toggle Button
Make one of the buttons visible then just toggle the visibility from View.VISIBLE to View.GONE and do the opposite for the other button.
You can try this:
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(startButton.getText().equalsIgnoreCase("Start")) {
startTime = SystemClock.uptimeMillis();
myHandler.postDelayed(updateTimerMethod, 0);
}
else if(startButton.getText().equalsIgnoreCase("Pause")) {
timeSwap += timeInMillies;
myHandler.removeCallbacks(updateTimerMethod);
}
}
});
Related
I have a widget with a button that users must press within a given interval. The button works fine and resets the interval but I want the button to change colour green -> amber -> red depending on time left. I have no problem changing the text on the button using remote views with code like this:
RemoteViews views =new RemoteViews(context.getPackageName(), R.layout.example_widget);
views.setCharSequence(R.id.example_widget_button, "setText", buttonText);
But I can not make any sort of code change the button colour. I've tried several things along the lines of:
views.setCharSequence(R.id.example_widget_button, "setBackgroundTint", "#039be5");
I have also tried using a drawable background and changing that. I'm missing something really obvious -it must be possible- I just can't find an example that works in my context.
Can anyone point me?
You can do this:
views.setInt(R.id.example_widget_button, "setBackgroundColor", android.graphics.Color.BLACK)`;
and you change the color to be what you want at that time.
You can either use Handler or CountDownTimer.
If you want to use Handler, here is the example:
long totalTime = 10000;
long warningTime = 6000;
long alertTime = 30000;
Runnable warningColorChangeRunnable = new Runnable() {
#Override
public void run() {
button.setBackgroundColor(getResources().getColor(R.color.colorWarning));
}
};
Runnable alertColorChangeRunnable = new Runnable() {
#Override
public void run() {
button.setBackgroundColor(getResources().getColor(R.color.colorAlert));
}
};
final Handler handler = new Handler();
handler.postDelayed(warningColorChangeRunnable, totalTime - warningTime);
handler.postDelayed(alertColorChangeRunnable, totalTime - alertTime);
button.setOnClickListener(new OnClickListener() {
#Override public void onClick(View view) {
handler.removeCallbacks(warningColorChangeRunnable);
handler.removeCallbacks(alertColorChangeRunnable);
}
});
If you want to use CountDownTimer, here is the example:
long totalTime = 10000;
long warningTime = 6000;
long alertTime = 30000;
long interval = 1000;
CountDownTimer timer = new CountDownTimer(totalTime, 1000) {
public void onTick(long millisUntilFinished) {
if (millisUntilFinished <= warningTime && millisUntilFinished > warningTime - interval) {
button.setBackgroundColor(getResources().getColor(R.color.colorWarning));
}
if (millisUntilFinished <= alertTime && millisUntilFinished > alertTime - interval) {
button.setBackgroundColor(getResources().getColor(R.color.colorAlert));
}
}
public void onFinish() {
// Maybe show a failure dialog
}
}.start();
button.setOnClickListener(new OnClickListener() {
#Override public void onClick(View view) {
timer.cancel();
}
});
Similar query: wait until all threads finish their work in java
Hello,
I'm developing android application that contains some kind of count down timer. My problem is, that I have multiple count down timers, that sets text of TextView and have to work separately (first count down timer has to wait until the second one is finished etc.)
See code:
MyCountDownTimer.java
public class MyCountdownTimer extends CountDownTimer {
TextView tv;
// default constructor
public MyCountdownTimer (long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
// constructor
public MyCountdownTimer(int hours, int mins, int secs,
long countDownInterval, TextView tv) {
super(3600000 * hours + 60000 * mins + secs * 1000, countDownInterval);
this.tv = tv;
// all other settings
}
// when finished, set text of textview to done
#Override
public void onFinish() {
tv.setText("done!");
}
// when working periodically update text of text view to value of time left
#Override
public void onTick(long millisUntilFinished) {
tv.setText(/*function setting text of TextView based on time left*/);
}
}
Timer.java
public class Timer extends Fragment {
Button bStart;
Button bStop;
TextView tvShowTime;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.timer, container, false);
}
public void onStart() {
super.onStart();
bStart = (Button) getView().findViewById(R.id.bTimerStart);
bStop = (Button) getView().findViewById(R.id.bTimerStop);
tvShowTime = (TextView) getView().findViewById(R.id.showTime);
// setting on button start click
bStart.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
timerStart();
}
});
// setting on button stop click
bStop.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
timerStop();
}
});
}
private void timerStart() {
bStart.setClickable(false);
int repeat = 2;
int hour, mins, secs;
for (int i = 0; i < 2 * repeat; i++) {
if (i % 2 == 0) {
// setting working count down timer values
mins = 1;
} else {
// setting resting count down timer values
secs = 30;
}
timerCount = new MyCountdownTimer(hours, mins, secs, REFRESH_RATE,
tvShowTime);
timerCount.start();
//////////////////////////////////////////////////
// HERE I WANT TO WAIT UNTIL COUNTDOWN IS DONE //
// ATM SECOND, THIRD AND FOURTH COUNT DOWN //
// TIMER IS STARTED //
//////////////////////////////////////////////////
}
}
-- EDIT --
At the end I did 2 CountDownTimers where first one calls in onFinish() second one and second one calls the first one until repeat = 0;
In final it was the best sotution for me. Anyway thanks for help, #Triode's answer helped me a lot
Start your SECOND, THIRD AND FOURTH COUNT DOWN TIMER in onFinish() of Your MyCountdownTimer
I think you have to put down the timerStop() method implementation and do not try to hide it,you need answer but you don't want others to benifit :s
I am working on making a clock similar to an abacus. My problem is that I cannot understand why my image resets after each second instead of continuing on to the right. My idea is that I need to use a different type of animation possibly? Here is my code so far:
public class MainActivity extends Activity implements AnimationListener {
Button start, stop;
TextView time;
LinearLayout layout;
Animation movement;
private Handler mHandler = new Handler();
private long startTime;
private long elapsedTime;
private final int REFRESH_RATE = 1000;
private String seconds;
private long secs;
private boolean stopped = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.buttonStart);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Start animation on each image
if(stopped){
startTime = System.currentTimeMillis() - elapsedTime;
}
else{
startTime = System.currentTimeMillis();
}
mHandler.removeCallbacks(startTimer);
mHandler.postDelayed(startTimer, 0);
}
});
stop = (Button) findViewById(R.id.buttonStop);
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mHandler.removeCallbacks(startTimer);
stopped = true;
}
});
time = (TextView) findViewById(R.id.textTime);
// Get the layouts
layout = (LinearLayout) findViewById(R.id.linearLayout1);
// Create animation for right image
movement = AnimationUtils.loadAnimation(this, R.layout.animation_test);
movement.setAnimationListener(this);
}
// Listen for animations to be finished
// There are more efficient ways, I'm just being lazy.
public void onAnimationEnd(Animation animation) {
// or do whatever it is you wanted to do here, like launch another activity?
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationStart(Animation animation) {
}
private Runnable startTimer = new Runnable() {
public void run() {
elapsedTime = System.currentTimeMillis() - startTime;
update(elapsedTime);
mHandler.postDelayed(this,REFRESH_RATE);
}
};
private void update (float time){
secs = (long)(time/1000);
layout.startAnimation(movement);
secs = secs % 60;
seconds=String.valueOf(secs);
if(secs == 0){
seconds = "00";
}
if(secs <10 && secs > 0){
seconds = "0"+seconds;
}
/* Setting the timer text to the elapsed time */
((TextView)findViewById(R.id.textTime)).setText(seconds);
}
}
My animation.xml is as follows
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="15%p"
android:fromYDelta="0"
android:toYDelta="0%"
android:duration="500"
android:zAdjustment="top"/>
I am at a standstill, been trying to read through the Development Sections, I just can't find the right solution or must be overlooking something.
Try adding:
android:fillEnabled="true"
android:fillAfter="true"
to your animation.
If you are targeting Android 3.0 or later, you can use the new animation framework instead: http://developer.android.com/guide/topics/graphics/prop-animation.html
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.
I am implementing a countup timer and I follow an example from StackoverFlow.
In my version, I will press the Begin button to start counting and the Stop button to stop.
But the problem is that the counting start immediately after i enter the activity.
Any idea how to make it the way i want?
public class StartActivity extends Activity
{
Button beginRecordingButton;
TextView timer;
long startTime;
long countup;
#Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.startactivity);
beginRecordingButton = (Button) findViewById(R.id.BeginRecording);
timer = (TextView) findViewById(R.id.timer);
final Chronometer stopwatch = (Chronometer) findViewById(R.id.chrono);
startTime = SystemClock.elapsedRealtime();
stopwatch.setOnChronometerTickListener(listener);
beginRecordingButton.setOnClickListener(new OnClickListener()
{
int counter = 0;
public void onClick(View v)
{
if (counter % 2 == 0)
{
stopwatch.start();
beginRecordingButton.setText("Stop");
}
if (counter % 2 == 1)
{
stopwatch.stop();
beginRecordingButton.setText("Begin");
}
counter++; //counter is used for knowing it is stop or begin
}
});
}
private OnChronometerTickListener listener = new OnChronometerTickListener()
{
public void onChronometerTick(Chronometer chronometer)
{
String text;
countup = (SystemClock.elapsedRealtime() - chronometer.getBase())/1000;
if(countup%60<10)
{
text = (countup/60) + ":0" + (countup%60);
}
else
{
text = (countup/60) + ":" + (countup%60);
}
timer.setText(text);
}
};
}
I found the solution by doing follow:
long test;
test = (SystemClock.elapsedRealtime() - stopwatch.getBase())/1000;
Log.i(TAG, = (SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000 - test;
basically String.valueOf(test));
stopwatch.start();
countup the idea is to subtract the passing time if i press the start button so it goes from 0