Wednesday 12 February 2014

Count Down Timer

Hi Friends,

Today i am going to explain you about Count Down Timer in android. Schedule a countdown until a time in the future, with regular notifications on intervals along the way. below is the example of showing a 10 second countdown in a text field:


Example:




Code:

activity_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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>


MainActivity.java


package in.androiddevelopmentanddiscussion.countdowntimer1;


import android.os.Bundle;

import android.os.CountDownTimer;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {


TextView tv;

Button btn;

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

tv = (TextView)findViewById(R.id.textView1);
btn = (Button)findViewById(R.id.button1);

btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

new CountDownTimer(11000, 1000) {

    public void onTick(long millisUntilFinished) {

        tv.setText("Time left : " + millisUntilFinished / 1000+"sec");
    }

    public void onFinish() {

        tv.setText("done!");
    }
 }.start();
}
});


}

@Override

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


}


Download full project from here: 

No comments:

Post a Comment