main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/androidtimer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Android Timer"
android:textSize="40sp"
android:textStyle="bold"
android:textColor="#FF0000"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="bottom|center" >
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FF0000"
android:text=" start "
android:textSize="35sp"
android:textColor="#FFFFFF"
android:onClick="startTimer"
/>
<View
android:layout_width="20dp"
android:layout_height="1dp"/>
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FF0000"
android:text=" stop "
android:textSize="35sp"
android:textColor="#FFFFFF"
android:onClick="stopTimer"
/>
</LinearLayout>
</LinearLayout>
The View objects are used just to create some space between two buttons. Also you can see that we have used a new linear layout within a linear layout to display two buttons in a horizontal row.
TimerActivity.java
package com.example.timer;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.View;
import android.widget.TextView;
public class TimerActivity extends Activity {
TimerTask timerTask;
int n=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startTimer(View view) {
final Handler handler = new Handler();
Timer ourtimer = new Timer();
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
TextView timer = (TextView)findViewById(R.id.androidtimer);
timer.setText(n + " Seconds");
n++;
}
});
}};
ourtimer.schedule(timerTask, 0, 1000);
}
public void stopTimer(View view) {
timerTask.cancel();
timerTask=null;
n=0;
}
}
Excellent post.it is very helpful.
ReplyDeleteandroid apps development
very helpful !!
ReplyDeletecould you explain the "0"and "1000" of this line :
ourtimer.schedule(timerTask, 0, 1000);
Thanks
ReplyDeleteThis article is very much helpful and i hope this will be an useful information for the needed one. Keep on updating these kinds of
ReplyDeleteinformative things...
Mobile App Development Company
Mobile App Development Company in India
Mobile App Development Companies
This comment has been removed by the author.
ReplyDelete