Can updating a TextView off the UI Thread cause an

2019-09-12 04:09发布

If a View is manipulated (ie, a TextView's text) in OnCreateView() (which is not on UI thread from my understanding), could it cause an exception in it (when this statement finally executes and trys to update the TextView, whenever that may be)?

For example, when the set text doesn't actually show up on the screen widget, could an exception have occurred that prevented it from showing that is eaten by the UI thread (or should the exception show up in the logger regardless)?

public class RecordView : Fragment
{
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle)
    {
        base.OnCreateView(inflater, container, bundle); 

        ViewGroup thisView = (ViewGroup) inflater.Inflate(Resource.Layout.Record, container, false);

        TextView tvData = thisView.FindViewById<TextView>(Resource.Id.tv_data);

        tvData.Text = "can this cause exception in UI thread?";

        return thisView;
    }   
}

2条回答
萌系小妹纸
2楼-- · 2019-09-12 04:41

OnCreateView() is always called on the Main Thread, so is every lifecycle method of fragments. Actually, every method ever called from the entry point runs on the ui thread by default if not explicitly called from another thread.

No, if you try to change a view from another thread, an uncaught exception is thrown, crashing the app. There is no silent failing in this case.

also, you do not need to call super in OnCreateView(), the base method is empty.

I do not know how C# implements field access, is it mapped to a setter method automatically? if not, you HAVE TO use the setter method instead of accessing the field directly, because setText() does more than just changing a String field.

查看更多
霸刀☆藐视天下
3楼-- · 2019-09-12 04:45

I can't address the specifics of your code but when trying to update a TextView (or EditView) from off the UI thread it will crash but it should show up in the logcat.

Here's an example of updating a TextView from a different thread.

public void addLine(String line){          //line is the text being passed in

    final String msg = line;               //this is critical!
    runOnUiThread(new Runnable(){
        @Override
        public void run() {
            rcvd.append("\n" + msg);      //rcvd is a TextView and we're just 
        }                                 //adding a line of text
    });
}

As for exceptions occurring but not showing up, I can't say with certainty but it is possible for the debugger to detach and it looks like your app just crashed. I went through this recently while stepping through, and at a certain point everything just died. In my case it was while stepping out of a BroadcastReceiver's onReceive method. Eventually I figured out that it only happened while stepping through, not when left to run.

Hopefully someone a lot smarter than me will weigh in but in the mean time, good luck!

查看更多
登录 后发表回答