Last active
March 22, 2017 13:35
-
-
Save jkpark/2163ac1d2bc82361ae9771bc722b5ebf to your computer and use it in GitHub Desktop.
TextView with Date
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MDateView extends View { | |
private final static String FORMAT_DEFULAT = "yyyy.MM.dd"; | |
private boolean isTickable = false; | |
private boolean isColon = true; | |
private Calendar mCalendar; | |
private Runnable mTickerRunnable; | |
private Handler mHandler; | |
private String mFormat = FORMAT_DEFULAT; | |
private String mDateString = "", mTimeString = ""; | |
private Paint mDatePaint, mTimePaint; | |
public MDateView(Context context) { | |
super(context); | |
initClock(context); | |
} | |
public MDateView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
initClock(context); | |
} | |
private void initClock(Context context) { | |
if (mCalendar == null) { | |
mCalendar = Calendar.getInstance(); | |
} | |
mDatePaint = new Paint(Paint.ANTI_ALIAS_FLAG); | |
mDatePaint.setColor(Color.argb(255, 255, 255, 255)); | |
mDatePaint.setTextSize(18); | |
mDatePaint.setTextAlign(Align.LEFT); | |
mTimePaint = new Paint(Paint.ANTI_ALIAS_FLAG); | |
mTimePaint.setColor(Color.argb(255, 255, 255, 255)); | |
mTimePaint.setTextSize(24); | |
mTimePaint.setTextAlign(Align.LEFT); | |
} | |
@Override | |
protected void onDraw(Canvas canvas) { | |
canvas.drawText(mDateString, 5, 35, mDatePaint); | |
int offsetX = 92; | |
float time_X_Pos = (120 - mTimePaint.measureText(mTimeString, 0, mTimeString.length())) / 2.0f;// center align | |
canvas.drawText(mTimeString, offsetX + time_X_Pos, 35, mTimePaint); | |
} | |
@Override | |
protected void onAttachedToWindow() { | |
super.onAttachedToWindow(); | |
isTickable = true; | |
mHandler = new Handler(); | |
mTickerRunnable = new Runnable() { | |
public void run() { | |
if (!isTickable) | |
return; | |
mCalendar.setTimeInMillis(System.currentTimeMillis()); | |
mDateString = DateFormat.format(mFormat, mCalendar).toString(); | |
mTimeString = DateFormat.format("k" + (isColon ? ":" : " ") + "mm", mCalendar).toString(); | |
invalidate(); | |
long now = SystemClock.uptimeMillis(); | |
long next = now + (1000 - now % 1000); | |
isColon = !isColon; | |
mHandler.postAtTime(mTickerRunnable, next); | |
} | |
}; | |
mTickerRunnable.run(); | |
} | |
@Override | |
protected void onDetachedFromWindow() { | |
super.onDetachedFromWindow(); | |
isTickable = false; | |
} | |
public void setFormat(String format) { | |
if (mFormat == format) | |
return; | |
mFormat = format; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment