Android Analog, Digital And Text Clock Example

Android provides three clock widgets that you can use to implement a clock. They are android.widget.AnalogClock, android.widget.DigitalClock and android.widget.TextClock. The AnalogClock and DigitalClock class have been deprecated since Android SDK version 1.7, but they can still be used. TextClock class is recommended.

1. android.widget.AnalogClock

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

1.1 The AnalogClock Class Important Properties.

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

1.2 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 a time modify function yourself.
  3. Can not get time from AnalogClock class directly, use java.util.Calendar to get current time instead.

1.3 AnalogClock Example.

  1. Below is the analog clock example image.
    analog-clock-eaxmple
  2. 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.
  3. 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"/>
  4. Use the above layout XML in your Activity code.

2. android.widget.DigitalClock

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

2.1 DigitalClock Disadvantage.

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

2.2 DigitalClock Example.

  1. Below is the digital clock example image.
    digital-clock-example
  2. Just copy the 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. Use the TextClock class has the below benefits.

3.1 TextClock Class Benefits.

  1. Can show, set, and get both date and time.
  2. Support date-time format customization.

3.2 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.

3.3 Main TextClock Method.

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

3.4 TextClock Example.

  1. Below is the text clock example image.
    textclock-example
  2. Use the below XML code in your layout file to implement the 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"/>
  3. Please Note: When you use the TextClock XML tag, you may encounter an error message like “view requires API level 17 (Current min is 15)” like below. This is because your project SDK version is 15 and TextClock requires version 17. Follow the below steps to resolve this issue.
  4. In the Android Studio left project tree view panel.
  5. Select Project in the drop-down list.
  6. Click app/build.gradle file.
  7. Change minSdkVersion from 15 to 17 in the right panel.

4. Full Example

If the above video can not be shown, you can see it from the URL https://youtu.be/Nbfk8oLnaY8.

4.1 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>

4.2 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

1 thought on “Android Analog, Digital And Text Clock Example”

  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

Leave a Comment

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.