package ******************;
import android.content.Context;
import android.support.annotation.Nullable;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Created by xidong on 2017/4/7.
*自定義數(shù)字時(shí)鐘的view
*/
public class NetworkClock extends TextView {
private CharSequence mFormat;
private Calendar mTime;
private long mCurrent;
public long getmCurrent() {
return mCurrent;
}
public void setmCurrent(long mCurrent) {
this.mCurrent = mCurrent;
}
public NetworkClock(Context context) {
super(context);
init();
}
public NetworkClock(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mFormat = "HH:mm:ss";
mTime = Calendar.getInstance();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
getTimeFromNetwork();
}
private void getTimeFromNetwork() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
//? ? ? ? ? ? Date data = format.parse("2017-04-07 12:12:20");
//? ? ? ? ? ? mCurrent = data.getTime();
onTimeChanged(mCurrent);
getHandler().postDelayed(mTicker, 1000 - mCurrent % 1000);
} catch ( Exception e) {
e.printStackTrace();
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
getHandler().removeCallbacksAndMessages(null);
}
private final Runnable mTicker = new Runnable() {
public void run() {
mCurrent += 1000;
onTimeChanged(mCurrent);
getHandler().postDelayed(mTicker, 1000);
}
};
private void onTimeChanged(long current) {
mTime.setTimeInMillis(current);
setText(DateFormat.format(mFormat, mTime));
}
}