先上效果图:
然后就是自己定义的linearlayout了。
/** * 倒计时 3文本 * Created By Fangchao On 2015/3/12 */public class TimeTextView extends LinearLayout { private long mday, mhour, mmin, msecond;//天,小时,分钟,秒 private boolean run = false; //是否启动了 Timer timer = new Timer(); TextView Vhour, Vmin, Vseconds; public TimeTextView(Context context) { super(context); iniUI(context); } public TimeTextView(Context context, AttributeSet attrs) { super(context, attrs); iniUI(context); } public void iniUI(Context context) { LayoutInflater mInflater = LayoutInflater.from(context); View myView = mInflater.inflate(R.layout.view_time_texviews, null); Vhour = (TextView) myView.findViewById(R.id.tv_hours); Vmin = (TextView) myView.findViewById(R.id.tv_minutes); Vseconds = (TextView) myView.findViewById(R.id.tv_seconds); addView(myView); } public TimeTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); iniUI(context); } private Handler mHandler = new Handler() { }; public boolean isRun() { return run; } public void setRun(boolean run) { this.run = run; } public void start() { if (!isRun()) { setRun(true); timer.schedule(task, 1000, 1000); } } /** * 依据传进来的时间差 为textview 赋值 * * @param duration */ public void setTimes(long duration) { Date date = new Date(duration); Date date1 = new Date(1L); /*mday = duration / 60000 / 60 / 24; mhour = (duration - mday * 6000 * 60 * 24) / 3600000; mmin = (duration - mhour * 6000 * 60 - mday * 3600000 * 24) / 60000; msecond = (duration - mmin * 60000 - mhour * 3600000 - mday * 3600000 * 24) / 60000;*///须要改动,測试用 mday = date.getDay(); mhour = date.getHours(); mmin = date.getMinutes(); msecond = date.getSeconds(); } /** * 倒计时计算 */ private void ComputeTime() { msecond--; if (msecond < 0) { mmin--; msecond = 59; if (mmin < 0) { mmin = 59; mhour--; if (mhour < 0) { // 倒计时结束 mhour = 24; mday--; } } } } TimerTask task = new TimerTask() { @Override public void run() { mHandler.post(new Runnable() { // UI thread @Override public void run() { run = true; ComputeTime(); if (mday < 0) { setVisibility(View.GONE); setRun(false); } Vhour.setText(mhour < 10 ? ("0" + mhour) : mhour + ""); Vseconds.setText(msecond < 10 ?
("0" + msecond) : msecond + ""); Vmin.setText(mmin < 10 ? ("0" + mmin) : mmin + ""); } }); } }; }
用的时候直接在须要的地方直接把TimeTextview 放上即可了,
举个样例吧,能够在adapter中设置倒计时时长。。。。@Override public void onBindHeaderView(RecyclerView.ViewHolder holder, int position) { HeaderViewHolder headViewHolder = (HeaderViewHolder) holder; long duration= 1426244976513L + 200 * 1000 - TimeUtils.getCurrentTimeInLong(); Log.e("long///", TimeUtils.getCurrentTimeInLong() + ""); if (!headViewHolder.timeTextView.isRun()) { headViewHolder.timeTextView.setTimes(duration); headViewHolder.timeTextView.start(); } }