Analog and Digital clock in Android example



Android analog and digital clock widget is simple to code, since it’s provided by default in Android OS. These are available under  android.widget.AnalogClock and android.widget.DigitalClock components. Both these are just for display purpose, hence time cannot be modified. The below code is a self-explanatory one, have a look and post your comments.


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/background_dark"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="5dp"
        android:text="Analog Clock"
        android:textColor="@android:color/white" />

    <AnalogClock
        android:id="@+id/analogClock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:text="Digital Clock"
        android:textColor="@android:color/white" />

    <DigitalClock
        android:id="@+id/digitalClock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="5dp"
        android:background="@android:color/darker_gray"
        android:text="DigitalClock" />

</LinearLayout>

Main_Activity.java

package com.example.analogdigitalclock;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.AnalogClock;
import android.widget.DigitalClock;

public class MainActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  AnalogClock ac = (AnalogClock) findViewById(R.id.analogClock1);
  DigitalClock dc = (DigitalClock) findViewById(R.id.digitalClock1);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

Download Eclipse project here

Analog Digital clock





Reactions:

1 comment :

  1. is it possible to display digitalClock1 in the text view element without the digital clock element??

    ReplyDelete