o7planning

Android TextClock Tutorial with Examples

  1. Android TextClock
  2. Example of TextClock

1. Android TextClock

In Android, TextClock is a subclass of TextView. It is used to display the current date and time of the system.
TextClock requires API Level 17 (Android 4.2) or a later version. So if you want to use the TextClock in your project, you need to change the value of minSdkVersion in the build.gradle (Module: app) file, and make sure it is greater than or equal to 17.
TextClock is not available in the Palette of the design window, probably because it is not a common component. Therefore, you need to use the following XML code to add it to the interface.
<!--
     IMPORTANT NOTE:
     You may get "Exception raised during rendering" error on design screen.
-->
<TextClock
    android:id="@+id/textClock"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:format12Hour="hh:mm:ss a" />
Note: You may receive an error notification when you try to design the interface in the presence of the TextClock. This issue has been confirmed on Android Studio 3.x, 4.0. Some people have submitted their reports to Google to address the problem:
Exception raised during rendering.

java.lang.NullPointerException
    at android.content.ContentResolver.registerContentObserver(ContentResolver.java:2263)
    at android.widget.TextClock.registerObserver(TextClock.java:626)
    at android.widget.TextClock.onAttachedToWindow(TextClock.java:545)
    at android.view.View.dispatchAttachedToWindow(View.java:19575)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
    at android.view.AttachInfo_Accessor.setAttachInfo(AttachInfo_Accessor.java:42)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:335)
    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:396)
    at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:209)
    at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:608)
    at com.android.tools.idea.rendering.RenderTask.lambda$inflate$6(RenderTask.java:734)
    at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Anyway, I have resolved this problem by creating a subclass of the TextClock and using it (See more in the example).
TextClock has two modes of time display:
  • 12Hour Mode
  • 24Hour Mode
First, the TextClock object will call the is24HourModeEnabled() method to check if the user's device is using 24-hour mode. Note: User can switch between 12-hour mode and 24-hour mode in the Settings section of the device.
There are 2 possibilities:
1 - If the user's device is in 24-hour mode.
  • TextClock will display the time according to the format of the value returned from getFormat24Hour(), in case it is not null.
  • Otherwise, it will display the time according to the format of the value returned from getFormat12Hour(), in case it is not null.
  • Otherwise, it will display the time in the default format, "h:mm a", for example.
2 - If the user's device is in 12-hour mode,
  • TextClock will display the time according to the format of the value returned from getFormat12Hour(), in case it is not null.
  • Otherwise, it will display the time according to the format of the value returned from getFormat24Hour(), in case it is not null.
  • Otherwise, it will display the time in the default format, "h:mm a", for example.

2. Example of TextClock

Great, now on Android Studio create a project:
  • File > New > New Project > Empty Activity
    • Name: TextClockExample
    • Package name: org.o7planning.textclockexample
    • Language: Java
TextClock requires API Level 17 (Android 4.2) or a later version. So if you want to use the TextClock in your project, you need to change the value of minSdkVersion in the build.gradle (Module: app) file, and make sure it is greater than or equal to 17.
As mentioned above, you may receive an error notification when attempting to design the interface in the presence of the TextClock. It is possible that the issue will be addressed by Google in later versions of Android Studio. But for now, to overcome this problem, we create the MyTextClock class extending from the TextClock, then use it.
MyTextClock.java
package org.o7planning.textclockexample;

import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.TextClock;

import androidx.annotation.RequiresApi;

public class MyTextClock extends TextClock {

    public MyTextClock(Context context) {
        super(context);
        //
        this.setDesigningText();
    }

    public MyTextClock(Context context, AttributeSet attrs) {
        super(context, attrs);
        //
        this.setDesigningText();
    }

    public MyTextClock(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //
        this.setDesigningText();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public MyTextClock(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        //
        this.setDesigningText();
    }

    private void setDesigningText() {
        // The default text is displayed when designing the interface.
        this.setText("11:30:00");
    }

    //
    // Fix error: Exception raised during rendering.
    //
    // java.lang.NullPointerException
    //    at android.content.ContentResolver.registerContentObserver(ContentResolver.java:2263)
    //    at android.widget.TextClock.registerObserver(TextClock.java:626)
    //    at android.widget.TextClock.onAttachedToWindow(TextClock.java:545)
    //    at android.view.View.dispatchAttachedToWindow(View.java:19575)
    //    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
    //    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
    //    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
    //    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
    //    at android.view.AttachInfo_Accessor.setAttachInfo(AttachInfo_Accessor.java:42)
    //    at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:335)
    //    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:396)
    //    at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:209)
    //    at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:608)
    //    at com.android.tools.idea.rendering.RenderTask.lambda$inflate$6(RenderTask.java:734)
    //    at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
    //    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    //    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    //    at java.lang.Thread.run(Thread.java:748)
    @Override
    protected void onAttachedToWindow() {
        try {
            super.onAttachedToWindow();
        } catch(Exception e)  {
        }
    }

}
Design the application interface:
Note: You need to Re-Build project, and then you will see MyTextClock appear on the Palette of design window.
Set textSize, textStyle, textColor, format12Hour, format24Hour for TextClock(s).
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <!-- 12 Hour Mode -->
    <org.o7planning.textclockexample.MyTextClock
        android:id="@+id/myTextClock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:format12Hour="hh:mm:ss a"
        android:format24Hour="@null"
        android:textColor="#80CC28"
        android:textSize="45dp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!-- 24 Hour Mode -->
    <org.o7planning.textclockexample.MyTextClock
        android:id="@+id/myTextClock2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:format12Hour="@null"
        android:format24Hour="yyyy-MM-dd HH:mm:ss"
        android:textColor="#F1511B"
        android:textSize="30dp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/myTextClock" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package org.o7planning.textclockexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextClock;

public class MainActivity extends AppCompatActivity {

    private TextClock textClock;
    private TextClock textClock2;

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

        this.textClock = (TextClock) this.findViewById(R.id.myTextClock);
        this.textClock2 = (TextClock) this.findViewById(R.id.myTextClock2);

        // Disable 24 Hour mode (To use 12 Hour mode).
        // (Make sure getFormat12Hour() is not null).
        this.textClock.setFormat24Hour(null);

        // Disable 12 Hour mode (To use 24 Hour mode).
        // (Make sure getFormat24Hour() is not null).
        this.textClock2.setFormat12Hour(null);
    }
}

Android Programming Tutorials

Show More