How to create a TextView in a thread?
I would like to know how to create a TextView inside of a t开发者_高级运维hread:
Thread t = new thread() {
public void run() {
for(int i = 0; i < 63; i++) {
TextView tv = new TextView();
tv.setText("What to do");
}
}
}
t.start();
What I don't understand what to do is what is suppose to be inside the construct method for TextView?
To answer your question: to create a
TextView
you must supply it with aContext
.Activity
andApplication
both extendContext
and are most often used where aContext
is necessary. In your case you should use the Activity whcih the createdTextView
will be shown in. So, to modify your code:class MyActivity extends Activity { public void someMethod() { Thread t = new Thread() { @override public void run() { for(int i = 0; i < 63; i++) { TextView tv = new TextView(MyActivity.this); tv.setText("What to do"); } } }; t.start(); } }
This is important, even though you didn't ask about it: a
TextView
is a UI control. It is only legal to create a UI control on the UI thread. Creating it in a different thread may lead to all kinds of trouble. One way of doing this from a different thread is to useActivity.runOnUiThread()
method:class MyActivity extends Activity { public void someMethod() { Thread t = new Thread() { @override public void run() { for(int i = 0; i < 63; i++) { runOnUiThread(new Runnable() { void run() { TextView tv = new TextView(MyActivity.this); tv.setText("What to do"); } }); } } }; t.start(); } }
Disclaimer: Even though I fixed some mistakes in the code above, I didn't test it. There can still be errors.
Try this,
Thread t = new thread(new Runnable()
{
public void run()
{
for(int i = 0; i < 63; i++)
{
runOnUiThread(new Runnable()
{
public void run()
{
TextView tv = new TextView(getApplicationContext());
tv.setText("What to do");
}
});
}
}
});
t.start();
you have to pass the Application Context to create Views and you can only modify UI on UI Thread.
Also if your thread is out of the activity class so you can call the runOnUiThread
activity's method, you may use the handler. You create an handler object in the main thread of the activity, and pass it as an argument to the wanted runnable object. Then into the runnable code you can use the post(Runnable r)
method of the handler to update the user interface from the thread without any problems.
精彩评论