Saturday, April 12, 2014

Why in the sub-thread can update UI? Like the following code!


 
public class MainActivity extends Activity {

@ Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
final TextView show = (TextView) findViewById (R.id.show);
new Thread ()
{
@ Override
public void run ()
{
show.setText ("child thread to update UI");
}
.} Start ();
}

Not to say that in the new UI thread can not update it? Why I created a new thread in the UI thread can also be updated successfully?
There labor you!
<-! Main posts under Banner (D4) -><-! Posts under the main text (D5) ->
Reply:
Their top play ah!
Reply:
It seems too late to quit a dangerous thread
Reply:
Android in order to limit the child thread updated UI, set up checking mechanism thread,
For example, from the sub-thread Textview.setText,
The log can be seen by the error, the position is thrown in android.view.ViewRoot.checkThread () (), from the literal meaning of view, this method is used to check the modified view of Thread () is the main thread.
This screening method in view of requestLayout () which is called, but requestLayout () in some cases will not be called:
if (mParent! = null) {
if (! mParent.isLayoutRequested ()) {
mParent.requestLayout ();
}
}

The only explanation is that more than two if one does not comply, leading to the back of the checkThread () () is not called, the child thread successfully modified the interface UI.
This may be in the early activity is created, layout, or other action initialization is not yet complete, check the thread does not lead to the occurrence of specific research questions will go under before we know it.

You can try your first case, before the new Thread modify textview thread to sleep for 2 seconds, this time again to modify the UI will throw an exception.
Reply:
LS up gesture of gratitude just know do not know the answer before there is such a case
Reply:
If you put this code into a button click event, he would first layout is displayed, followed by abnormal
will be reportednew Thread ()
{
@ Override
public void run ()
{
show.setText ("child thread to update UI");
}
.} Start ();

From the child thread to achieve in terms of the layout of the interface can be changed, but only a limit in the code, update ui will determine when the thread is not the main thread, if not they reported anomaly, which is a mechanism.
In fact, if at the right time in the simulator is running, even if the above code into the button's click event, and would be "child thread to update UI" is displayed before being given.
Reply:
3rd floor, the top long knowledge
Reply:
This exception error will be reported landlord, you want to see the log, and you almost always use this collapse
Reply:
Learning the top! ! ! !

No comments:

Post a Comment