接上篇Android 开发第五弹:简易时钟(闹钟) ,这次是一个时钟类应用,目前依旧是主要的功能,长得还是很挫。当然了,核心功能是有的……
时钟
先把简单的时钟给列出来吧,这里都写的很简单,即便要用世界各个城市的话,也只是相应的加上或减去几个小时。
新建TimeView类,并扩展自LinearLayout,然后布局文件和上一篇中那么写就好了。
<myapplication.nomasp.com.clock.TimeView
android : id = "@+id/tabTime"
android : layout_width = "match_parent"
android : layout_height = "match_parent"
android : orientation = "vertical">
<TextView
android : id = "@+id/tvTime"
android : textAppearance = "?android:attr/textAppearanceLarge"
android : layout_width = "match_parent"
android : layout_height = "match_parent"
android : gravity = "center" / >
</myapplication.nomasp.com.clock.TimeView>
// 实例化TextView控件
private TextView tvTime;
public TimeView(Context context) {
super(context);
}
public TimeView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TimeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onFinishInflate(){
super.onFinishInflate();
tvTime = (TextView)findViewById(R.id.tvTime);
tvTime.setText("H");
timeHandler.sendEmptyMessage(0);
}
private Handler timeHandler = new Handler() {
public void handleMessage(Message msg){
// 刷新时间
refreshTime();
if(getVisibility() == View.VISIBLE){
timeHandler.sendEmptyMessageDelayed(0, 1000);
}
}
};
// 刷新时间
private void refreshTime(){
Calendar c = Calendar.getInstance();
// 试着显示的时间格式
tvTime.setText(String.format("%d:%d:%d",
c.get(Calendar.HOUR_OF_DAY),
c.get(Calendar.MINUTE),
c.get(Calendar.SECOND)));
}
@Override
protected void onVisibilityChanged(View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if(visibility == View.VISIBLE){
timeHandler.sendEmptyMessage(0);
}else{
timeHandler.removeMessages(0);
}
}
就这些了,下面正式开始计时器的部分。
TimerView
TimerView类同样是扩展自LinearLayout,并且布局的写法也是如出一辙:
<myapplication.nomasp.com.clock.TimerView
android : id = "@+id/tabTimer"
android : layout_width = "match_parent"
android : layout_height = "match_parent"
android : orientation = "vertical">
<LinearLayout
android : orientation = "horizontal"
android : layout_width = "match_parent"
android : layout_height = "wrap_content">
&l