1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.TextView;
import android.os.Message;
public class CountDownView extends TextView
{
private final static int REFRESH_TIME = 1000;
private final static int TICK_WHAT = 42;
private long time_sec;
private boolean mRunning;
private Handler mHandler = new Handler()
{
public void handleMessage(Message m)
{
if (mRunning)
{
updateCount();
sendMessageDelayed(Message.obtain(this, TICK_WHAT), REFRESH_TIME);
}
}
};
public CountDownView(Context context)
{
super(context);
time_sec = 0;
mRunning = true;
updateRunning();
}
public CountDownView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
time_sec = 0;
mRunning = true;
updateRunning();
}
public CountDownView(Context context, AttributeSet attrs)
{
super(context, attrs);
time_sec = 0;
mRunning = true;
updateRunning();
}
public void setTime(long newTime)
{
time_sec = newTime;
}
private void updateRunning()
{
if (mRunning)
{
updateCount();
mHandler.sendMessageDelayed(Message.obtain(mHandler, TICK_WHAT), 1000);
}
else
mHandler.removeMessages(TICK_WHAT);
}
private void updateCount()
{
StringBuilder sb;
if (time_sec > SystemClock.elapsedRealtime())
{
sb = new StringBuilder();
long sec = (time_sec - SystemClock.elapsedRealtime()) / 1000;
int min = (int) (sec / 60);
sb.append(Integer.toString(min / 60));
sb.append(" heure(s) ");
min = min % 60;
sb.append(Integer.toString(min));
sb.append(" minute(s) et ");
sb.append(Integer.toString((int) (sec % 60)));
sb.append(" secondes");
this.setText(sb.toString());
}
else
this.setText("Enchère finie !");
}
@Override
protected void onDetachedFromWindow()
{
super.onDetachedFromWindow();
mRunning = false;
updateRunning();
}
@Override
protected void onWindowVisibilityChanged(int visibility)
{
super.onWindowVisibilityChanged(visibility);
mRunning = visibility == VISIBLE;
updateRunning();
}
} |
Partager