模拟时钟(AnalogClock)

模拟时钟(AnalogClock)

显示一个带时钟和分针的表面

会随着时间的推移变化

常用属性:

android:dial

可以为表面提供一个自定义的图片

下面我们直接看代码:

1.Activity

//模拟时钟
public class AnalogClockActivity extends Activity {

    private TextView timeTextView;
    private Handler handler;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.analog_clock);
        timeTextView = (TextView) findViewById(R.id.timeTextViewId);
//        Handler机制发送消息
        handler = new Handler() {
            public void handleMessage(Message msg) {
                timeTextView.setText(currentTime());
            }
        };
//        设置时间
        timeTextView.setText(currentTime());
        new CurrentTimeThread(handler).start();
    }

    private String currentTime() {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;
        int day = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);
        //(month < 10 ? "0" + month : month)三目运算法
        String currentTime = year + "-" + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day) + " "
                + (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute) + ":"
                + (second < 10 ? "0" + second : second);
        return currentTime;
    }

}
//开启一个子线程
class CurrentTimeThread extends Thread {
    private Handler handler;

    public CurrentTimeThread(Handler handler) {
        this.handler = handler;
    }

    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                handler.sendEmptyMessage(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

2.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp" >

    <DigitalClock
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textSize="20sp" />
<!-- 模拟时钟 -->
    <AnalogClock
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:dial="@drawable/biao_pan" />

    <TextView
        android:id="@+id/timeTextViewId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textSize="20sp" />

</LinearLayout>

3.效果图显示

posted @ 2016-05-08 14:18  疯狂的兔子!  阅读(1398)  评论(0编辑  收藏  举报