Set TextView value inside a thread in android
I am getting a crash under the fllowing circumstances. I am running a thread in the following way:
Thread t = new Thread(){
public void run() {
text.setText("hello");
}
};
t.start;
The crash occurs if I try to set the value of a TextView
in my xml, (the reference to text is already available).
Am I doing something fundamentally wrong? Kindly po开发者_如何学Goint out where am going wrong.
You can only access user interface components from the UI thread.
Android has a few things to make this easy, such as the method runOnUiThread and the class AsyncTask.
For more reading see Painless Threading and Processes and Threads in the Android documentation.
You should access android ui toolkit widgets only on the UI thread. Read http://developer.android.com/resources/articles/painless-threading.html.
use Handler class and check it for more relevant methods
Handler mHandler;
mHandler=new Handler(){
hdandleMessage(Message what){
text.setText("hello");
}
};
Thread t = new Thread(){
public void run()
{
mHandler.sendEmptyMessage(int what)
}
};
t.start;
精彩评论