从 UI 线程更新 TextView 会导致异常吗? [英] Can updating a TextView off the UI Thread cause an exception in it?

查看:24
本文介绍了从 UI 线程更新 TextView 会导致异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 View 中被操作(即 TextView 的 文本)OnCreateView()(根据我的理解,它不在 UI 线程上),它是否会导致异常(当此语句最终执行并尝试更新 TextView,无论何时)?

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)?

例如,当设置的文本实际上没有显示在屏幕小部件上时,是否可能发生异常阻止它显示被 UI 线程吃掉(或者异常是否应该出现在记录器中)?

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;
    }   
}

推荐答案

OnCreateView() 总是在主线程上调用,片段的每个生命周期方法也是如此.实际上,如果不是从另一个线程显式调用,则默认情况下,从入口点调用的每个方法都在 ui 线程上运行.

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.

另外,你不需要在OnCreateView()中调用super,基本方法是空的.

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

不知道C#是怎么实现字段访问的,是不是自动映射到setter方法?如果没有,您必须使用 setter 方法而不是直接访问该字段,因为 setText() 不仅仅是更改 String 字段.

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.

这篇关于从 UI 线程更新 TextView 会导致异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆