listview的item倒计时工具类使用方法
直接使用CountDown中utils复制到项目中去
1,ListActivity
/**
当可见状态-->不可见状态-->到可见状态,不在请求服务器获取截止时间,而是和系统启动时间相减
millis ==手机启动时间长+倒计时时长(从服务器获取倒计时时间)
*/ long elapsedRealtime = CountDownTask.elapsedRealtime();
/*********模拟数据,可以从服务器获取截止时间,和倒计时时间间隔********/
list = new ArrayList<>();
for (int i = 0; i < 50; i++) {
CountDownInfo countDownInfo = new CountDownInfo();
//偶数倒计时间隔为500ms,基数倒计时间隔1s
countDownInfo.countDownInterval = (i % 2 == 0) ? 500 : 1000;
//倒计时时间累计多加1s
countDownInfo.millis = (millis + 1000 * i);
list.add(countDownInfo);
}
/****************************************************/
2,
/**
*初始化adapter 然后开启倒计时任务
*/
private void initList() {
mAdapter = new CountDownAdapter(this, list);
mListView.setAdapter(mAdapter);
//开启计时器任务
startCountDown();
}
//创建任务
private void startCountDown() {
mCountDownTask = CountDownTask.create();
//把任务对象传到adapter中
mAdapter.setCountDownTask(mCountDownTask);
}
@Override
protected void onResume() {
super.onResume();
startCountDown();
}
@Override
protected void onPause() {
super.onPause();
cancelCountDown();
}
//取消
private void cancelCountDown() {
mAdapter.setCountDownTask(null);
mCountDownTask.cancel();
}
public class CountDownInfo {
//倒计时间隔
public long countDownInterval;
//倒计时时间长/截止时间
public long millis;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView = View.inflate(context,R.layout.list_item,null);
}
//Log.i("mengshirui","CountDownAdapter.getView.====="+position );
CountDownInfo countDownInfo = list.get(position);
//创建计时器倒计时,传/位置,倒计时对象,view
if(countDownInfo.millis>0){
if (countDownInfo.millis > 0) {
startCountDown(position, countDownInfo, convertView);
} else {
cancelCountDown(position, countDownInfo, convertView);
}
}
return convertView;
}
/**
* 开启计时器,成功回调******view-->对应的item的view ,millisUntilFinished-->剩余时间
* 结束直接返回item中的view
*/
private void startCountDown(final int position, CountDownInfo countDownInfo, View convertView) {
if(mCountDownTask!=null){
mCountDownTask.until(convertView, countDownInfo.millis, countDownInfo.countDownInterval, new CountDownTimers.OnCountDownListener() {
@Override
public void onTick(View view, long millisUntilFinished) {
//每过间隔时间所调用
//item的位置
TextView tv_position = (TextView) view.findViewById(R.id.tv_position);
tv_position.setText(String.valueOf(position));
//item剩余的时间
TextView countdown = (TextView) view.findViewById(R.id.countdown);
countdown.setText(String.valueOf(millisUntilFinished / 1000));
}
//倒计时结束
@Override
public void onFinish(View view) {
//item的位置
TextView tv_position = (TextView) view.findViewById(R.id.tv_position);
tv_position.setText(String.valueOf(position));
//item剩余的时间
TextView countdown = (TextView) view.findViewById(R.id.countdown);
countdown.setText("倒计时结束");
}
});
}
}
http://download.csdn.net/detail/mengshirui_/9562761