How update View TextView with timer Android runnable example

Update TextView by runnable. Handler, runnable, timer Android example.

public class TimerActivity extends Activity {
TextView hTextView;
Button hButton, hButtonStop;
private Handler mHandler = new Handler();
private int nCounter = 0;
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        hTextView = (TextView)findViewById(R.id.idTextView);
        hButton = (Button)findViewById(R.id.idButton);
        hButton.setOnClickListener(mButtonStartListener);
        hButtonStop = (Button)findViewById(R.id.idButtonStop);
        hButtonStop.setOnClickListener(mButtonStopListener);
    } // end onCreate
 
View.OnClickListener mButtonStartListener = new OnClickListener() {
	public void onClick(View v) {
		try {
			mHandler.removeCallbacks(hMyTimeTask);
         //        Parameters
         //        r  The Runnable that will be executed. 
         //        delayMillis  The delay (in milliseconds) until the Runnable will be executed. 
                       mHandler.postDelayed(hMyTimeTask, 1000); // delay 1 second
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
};
 
 
private Runnable hMyTimeTask = new Runnable() {
	   public void run() {
		   nCounter++;
	    	   hTextView.setText("Hallo from thread counter: " + nCounter);
	   }
	}; 
/**
 * 
 */
    View.OnClickListener mButtonStopListener = new OnClickListener() {
    	public void onClick(View v) {
    		 mHandler.removeCallbacks(hMyTimeTask);
 
    	}
    };
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
	android:id="@+id/idTextView"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<Button android:text="Button" 
android:id="@+id/idButton" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content"></Button>
 
 <Button android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:id="@+id/idButtonStop" 
 android:text="Stop"></Button> 
 
 
</LinearLayout>
This entry was posted in Android Examples Code and tagged , , , , . Bookmark the permalink.


Comments are closed.

45,470 views