您还可以创建自定义TextView
,它每秒或每分钟或每小时更新一次。这可以通过创建扩展TextView
并在该类中添加 Handler 的类来轻松完成。好处是您不必更新整个 ListView,TextView 会自动更新。
例子:
public class TextViewTimeCounter extends TextView {
private long mStartTime = 0;
private long mTimeNow = 0;
private int mDelay = 0;
private String mPart1 = "";
private String mPart2 = "";
private Handler mHandler;
public TextViewTimeCounter(Context context) {
super(context, null, 0);
}
public TextViewTimeCounter(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TextViewTimeCounter(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void startTimer(long delay, String part1, String part2){
mStartTime = System.currentTimeMillis();
mTimeNow = System.currentTimeMillis();
mDelay = delay;
mHandler = new Handler();
mHandler.postDelayed(r, delay);
convertDatesToMinutes(mStartTime, mTimeNow);
}
public void stopTimer(){
if(mHandler != null){
mHandler = null;
mStartTime = 0;
mTimeNow = 0;
}
}
public boolean isTimerRunning(){
return mHandler == null? false : true;
}
Runnable r = new Runnable() {
@Override
public void run(){
mTimeNow += mDelay;
convertDatesToMinutes(mStartTime, mTimeNow);
if(mHandler != null){
mHandler.postDelayed(r, mDelay);
}
}
};
public void convertDatesToMinutes(long start, long end){
long secs = (end - start);
long minute = (secs / (1000 * 60)) % 60;
long hour = (secs / (1000 * 60 * 60)) % 24;
String time = String.format(Locale.getDefault(), "%2d hours %2d minutes", hour, minute);
setText(mPart1 + time + mPart2);
}
用法:
TextViewTimeCounter timer = (TextViewTimeCounter)convertView.findViewById(R.id.start_logging_time_text);
timer.startTimer(10000, "Posted ", " ago");
输出将如下所示:
Posted 1 hours 5 minutes ago
如果您还想显示秒数,请将convertDatesToMinutes(long start, long end)
方法更改为:
public void convertDatesToMinutes(long start, long end){
long secs = (end - start);
long second = (secs / 1000) % 60;
long minute = (secs / (1000 * 60)) % 60;
long hour = (secs / (1000 * 60 * 60)) % 24;
String time = String.format(Locale.getDefault(), "%2d hours %2d minutes %2d seconds", hour, minute, second);
setText(mPart1 + time + mPart2);
}