Fragment中onCreateView和onViewCreated的区别 [英] Difference between onCreateView and onViewCreated in Fragment

查看:30
本文介绍了Fragment中onCreateView和onViewCreated的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方法的本质区别是什么?当我创建一个 TextView 时,我应该使用一个而不是另一个来提高性能吗?

What's the essential difference between these two methods? When I create a TextView, should I use one over the other for performance?

onCreateView() {
  root = some view
  View v = new View(some context);
  root.add(v);
  return root;
}


onViewCreated() {
  View v = new View(some context);
  getView().add(v);
}

推荐答案

我们在 onCreateView 中初始化视图时遇到一些崩溃.

We face some crashes initializing view in onCreateView.

您应该在 onCreateView 中扩充您的布局,但不应在 onCreateView 中使用 findViewById 初始化其他视图.

You should inflate your layout in onCreateView but shouldn't initialize other views using findViewById in onCreateView.

因为有时视图没有正确初始化.所以总是在 onViewCreated 中使用 findViewById(当视图完全创建时)并且它也将视图作为参数传递.

Because sometimes view is not properly initialized. So always use findViewById in onViewCreated(when view is fully created) and it also passes the view as parameter.

onViewCreated 是确保视图已完全创建.

onViewCreated is a make sure that view is fully created.

onViewCreated android 文档

onViewCreated android Documentation

onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) 返回后立即调用,但在任何保存的状态恢复到视图之前.一旦他们知道他们的视图层次结构已经完全创建,这给了子类一个初始化自己的机会.然而此时片段的视图层次结构并未附加到其父级.

Called immediately after onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) has returned, but before any saved state has been restored in to the view. This gives subclasses a chance to initialize themselves once they know their view hierarchy has been completely created. The fragment's view hierarchy is not however attached to its parent at this point.

这篇关于Fragment中onCreateView和onViewCreated的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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