Android Analog, Digital And Text Clock Example

Android provide three clock widget that you can use to implement clock. They are android.widget.AnalogClock, android.widget.DigitalClock and android.widget.TextClock. AnalogClock and DigitalClock has been deprecated since android sdk version 1.7, but they can still be used. TextClock is recommended.

1. android.widget.AnalogClock

android.widget.AnalogClock class extends android.view.View class. So if you want to customize analog clock, you can create a sub class and overwrite it’s onDraw() method. And implement the customization code in that method.

AnalogClock Important Properties.

  1. android:dial : A drawable resource id which is analog clock dial image.
  2. android:hand_hour : A drawable resource id which is analog clock hour hand image.
  3. android:hand_minute : A drawable resource id which is analog clock minute hand image.

AnalogClock Disadvantage.

  1. Can not set analog clock second hand image.
  2. Can not set time directly, you can create a sub class to implement modify time function yourself.
  3. Can not get time from AnalogClock class directly, use java.util.Calendar to get current time instead.

AnalogClock Example.

analog clock example

  1. Copy your clock_dial.jpgclock_hour_hand.png and clock_minute_hand.png  into your android project app / res / drawable folder. Please note, the hour hand and minute hand image’s background should be transparent.
  2. Copy below AnalogClock xml code in your layout xml file.
    <AnalogClock
        android:id="@+id/analogClock"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:dial="@drawable/clock_dial"
        android:hand_hour="@drawable/clock_hour_hand"
        android:hand_minute="@drawable/clock_minute_hand"/>
  3. Use above layout xml in your Activity code.

2. android.widget.DigitalClock

android.widget.DigitalClock is a sub class of android.wedget.TextView. It can only show digital hour and minute value. You can change time value font size, color, style etc use TextView’s properties.

DigitalClock Disadvantage.

  1. Can not modify time directly, you can create a sub class to implement set time function yourself.
  2. Can only get text value from DigitalClock to get Hour and Minute time value.

DigitalClock Example.

digital clock example
Just copy below xml code into your layout file, then you can see a digital clock in your activity.

<DigitalClock
    android:id="@+id/digitalClock"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textSize="35sp"
    android:textColor="@color/colorRed"
    android:textStyle="bold"
    android:layout_gravity="center_horizontal"/>

3. android.widget.TextClock

android.widget.TextClock is introduced since android sdk 1.7. It is recommended. TextClock has below benefits.

  1. Can show, set and get both date and time.
  2. Support date time format customization.
READ :   Android Change Orientation Without Restarting Activity Example

Main TextClock Atttibute.

  1. format12Hour : Set 12-hour system time format.
  2. format24Hour : Set 24-hour system time format.
  3. timeZone : Set time zone.
  4. drawableStart : Clock head image id.
  5. drawableEnd : Clock tail image id.

Main TextClock Method.

  1. is24HourModeEnabled() : Check whether the system is currently using 24-hour system. This is decided by OS, can not change in code.

TextClock Example.

textclock example

Use below xml code in your layout file to implement above TextClock example.

<TextClock
    android:id="@+id/textClock"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textSize="35sp"
    android:textColor="#00FF00"
    android:format12Hour="yyyy-MM-dd H:mm:ss EEEE"
    android:drawableStart="@mipmap/ic_launcher"
    android:drawableEnd="@mipmap/ic_launcher"/>

Please Note: When you use TextClock xml tag, you may encounter error message like “view requires API level 17 (Current min is 15)” like below.

android sdutio min sdk version issue

This is because your project sdk version is 15 and TextClock require version 17. Follow below steps to resolve this issue.

  1. In left project tree view panel.
  2. Select Project in the drop down list.
  3. Click app / build.gradle file.
  4. Change minSdkVersion from 15 to 17 in right panel.
    change android min sdk version in build.gradle

4. Full Example

android analogclock digitalclock textclock example

activity_clock.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.dev2qa.example.ClockActivity">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:scrollbars="vertical"
            android:scrollbarStyle="insideOverlay"
            tools:layout_editor_absoluteY="8dp"
            tools:layout_editor_absoluteX="8dp">

            <!-- AnalogClock Example -->
            <TextView
                android:id="@+id/textView10"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Analog Clock Example"
                android:textSize="25sp"
                android:textColor="@color/colorRed"/>
            <AnalogClock
                android:id="@+id/analogClock"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:dial="@drawable/clock_dial"
                android:hand_hour="@drawable/clock_hour_hand"
                android:hand_minute="@drawable/clock_minute_hand"/>
            <Button
                android:id="@+id/analogClockGetValueButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Get Analog Clock Time"/>

            <!-- DigitalClock Example -->
            <TextView
                android:id="@+id/textView9"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Digital Clock Example"
                android:textSize="25sp"
                android:textColor="@color/colorRed"/>
            <DigitalClock
                android:id="@+id/digitalClock"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textSize="35sp"
                android:textColor="@color/colorRed"
                android:textStyle="bold"
                android:layout_gravity="center_horizontal"/>
            <Button
                android:id="@+id/digitalClockGetValueButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Get Degital Clock Time"/>

            <!-- TextClock Example -->
            <TextView
                android:id="@+id/textView8"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Text Clock Example"
                android:textSize="25sp"
                android:textColor="@color/colorRed"/>
            <TextClock
                android:id="@+id/textClock"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textSize="35sp"
                android:textColor="#00FF00"
                android:format12Hour="yyyy-MM-dd H:mm:ss EEEE"
                android:format24Hour="yyyy/MM/dd EE H:mm:ss"
                android:drawableStart="@mipmap/ic_launcher"
                android:drawableEnd="@mipmap/ic_launcher"
                android:timeZone="GMT+00:00" />
            <Button
                android:id="@+id/textClockGetValueButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Get Text Clock Time"/>
            <Button
                android:id="@+id/textClockSetValueButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Change To BeiJing TimeZone"/>
        </LinearLayout>
    </ScrollView>
</android.support.constraint.ConstraintLayout>

ClockActivity.java

package com.dev2qa.example;

import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AnalogClock;
import android.widget.Button;
import android.widget.DigitalClock;
import android.widget.TextClock;

import java.util.Calendar;

public class ClockActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clock);

        final AnalogClock analogClock = (AnalogClock)findViewById(R.id.analogClock);
        Button getAnalogClockValueBtn = (Button)findViewById(R.id.analogClockGetValueButton);
        // Make button text original not all uppercase.
        getAnalogClockValueBtn.setAllCaps(false);

        getAnalogClockValueBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Can not get time value from AnalogCLock directly.
                // So get current time from system.
                long analogClockTime = Calendar.getInstance().getTimeInMillis();
                showTimeInDialog("Analog clock time is", analogClockTime);
            }
        });


        final DigitalClock digitalClock = (DigitalClock)findViewById(R.id.digitalClock);
        Button getDigitalClockValueBtn = (Button)findViewById(R.id.digitalClockGetValueButton);
        getDigitalClockValueBtn.setAllCaps(false);
        getDigitalClockValueBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Can only get time value from DigitalClock display text.
                String digitalTimeValue = (String)digitalClock.getText();
                showTimeInDialog("Digital clock time is " + digitalTimeValue, -1);
            }
        });


        final TextClock textClock = (TextClock)findViewById(R.id.textClock);
        final Button getTextClockValueBtn = (Button)findViewById(R.id.textClockGetValueButton);
        getTextClockValueBtn.setAllCaps(false);
        getTextClockValueBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StringBuffer msgBuffer = new StringBuffer();
                msgBuffer.append("TextClock has below attributes:\r\n");
                msgBuffer.append("Time " + textClock.getText() + " \r\n");
                msgBuffer.append("TimeZone " + textClock.getTimeZone() + "\r\n");
                msgBuffer.append("Is24HourMode " + textClock.is24HourModeEnabled() + "\r\n");
                msgBuffer.append("24-hour Format " + textClock.getFormat24Hour() + "\r\n");
                msgBuffer.append("12-hour Format " + textClock.getFormat12Hour() + "\r\n");

                showTimeInDialog(msgBuffer.toString(), -1);
            }
        });

        Button setTextClockValueBtn = (Button)findViewById(R.id.textClockSetValueButton);
        setTextClockValueBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // The time zone is GMT+00:00 in layout xml configure.
                // Change time zone to GMT+08:00, Bei Jing time zone.
                textClock.setTimeZone("GMT+08:00");
                // Click textClockGetValueButton again.
                getTextClockValueBtn.callOnClick();
            }
        });
    }

    /* Show timeLongValue use yyyy-MM-dd HH:MM:SS format in alert dialog. */
    private void showTimeInDialog(String timeSource, long timeLongValue)
    {
        AlertDialog alertDialog = new AlertDialog.Builder(ClockActivity.this).create();

        StringBuffer timeBuf = new StringBuffer();
        timeBuf.append(timeSource);

        if(timeLongValue!=-1) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(timeLongValue);
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);

            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);

            timeBuf.append(" : ");
            timeBuf.append(year);
            timeBuf.append("-");
            timeBuf.append(month+1);
            timeBuf.append("-");
            timeBuf.append(day);
            timeBuf.append(" ");
            timeBuf.append(hour);
            timeBuf.append(":");
            timeBuf.append(minute);
            timeBuf.append(":");
            timeBuf.append(second);
        }
        alertDialog.setMessage(timeBuf.toString());
        alertDialog.show();
    }
}

5. Reference

  1. android.widget.AnalogClock
  2. android.widget.DigitalClock
  3. android.widget.TextClock
(Visited 4,202 times, 1 visits today)

1 Comment


  1. Thank you very much for the explanation and examples I have benefited a lot
    But please want to help me in the example how to add a second hand to a widget analog clock application can you give me the code for it

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.