Android textclock example

TextClock is an android widget which can display current time in string format and will update time in each second. Using TextClock it is possible to provide both 24-hour formatted time as well as 12-hour formatted time. In this tutorial we learn how to create a TextClock in android.

Contents

  • Code for TextClock widget
  • Converting into 24 hour format and vice versa
  • Implementation steps(For beginners)

Code for TextClock widget

The implementation of TextClock is as simple as adding following XML code to your layout file.

<TextClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:format12Hour="hh:mm:ss a"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="#000000" />

Converting into 24 hour format and vice versa

For 24-hour formatted time just replace the line

android:format12Hour="hh:mm:ss a"

with

android:format24Hour="hh:mm:ss a"

Implementation steps (Will be helpful for beginners in android)

  • Create  a project in android studio.
  • Modify the layout file which is automatically created with your activity with the TextClock widget code

Create project in android studio

Refer Android beginners app development guide if you are beginner or if you don’t know how to create project in android studio.

Adding TextClock to layout

A layout file will be automatically created while you are doing this as new project ,if not right click on res->layout folder and click on New -> Layout resource file. Now add the following code in to the XML file created

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

<TextClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:format12Hour="hh:mm:ss a"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="#000000" />

</RelativeLayout>

Now simply click on the run button you will get the following output screen.

textclock in android
textclock in android

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

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