Sunday, May 20, 2012

runOnUiThread: Update UI Using runOnUiThread



Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

Example:

RunOnUiThreadExample.java:


package com.imrankhanandroid.runOnUiThreadExmp; import java.text.DateFormat; import java.util.Date; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class RunOnUiThreadExample extends Activity { /** Called when the activity is first created. */ TextView txtview; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtview=(TextView)findViewById(R.id.txtview); myThread(); } public void myThread(){ Thread th=new Thread(){ @Override public void run(){ try { while(true) { Thread.sleep(100); RunOnUiThreadExample.this.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub String currentDateTimeString = DateFormat. getDateTimeInstance().format(new Date()); txtview.setText(currentDateTimeString); } }); } }catch (InterruptedException e) { // TODO: handle exception } } }; th.start(); } }




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:orientation="vertical" > <TextView android:id="@+id/txtview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>


Download Source Code: RunOnUiThreadExample









0 comments:

Post a Comment

 
Powered by Blogger