In Android, the AnalogClock is a two-handed clock, one for hour indicator and the other for minute indicator. The DigitalClock is look like your normal digital watch on hand, which display hours, minutes and seconds in digital format.
Both AnalogClock
and DigitalClock
are UNABLE to modify the time, if you want to change the time, use “TimePicker” instead.
In this example I will show you how to implement both Analog and Digital Clock.
Let’s get start by creating a project in Eclipse IDE.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. (I kept my main activity name as MainActivity.java)
2. Create a layout file for MainActivtiy.java under res ⇒ layout folder. I named the layout file as activity_main.xml. In this layout i had taken one Analog and one Digital Clock.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:orientation="vertical" android:padding="5dp" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:gravity="center" android:text="Analog Clock" android:textSize="25sp" /> <AnalogClock android:id="@+id/analogClock1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:gravity="center" android:text="Digital Clock" android:textSize="25sp" /> <DigitalClock android:id="@+id/digitalClock1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" /> </LinearLayout> |
3. Now, come to MainActivity.java and add the following code. In this class we have to find the ids of both clocks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.analog_digital_clock_demo; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.widget.AnalogClock; import android.widget.DigitalClock; import com.android_analog_n_digital_clock_demo.R; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Just find both ID and it will automatically get the current device // timing and set time findViewById(R.id.analogClock1); findViewById(R.id.digitalClock1); } } |
4. Now, run the app and you will get the output as shown in video.
Thanks.
Subscribe to us and get the latest news.