【问题标题】:Difference between traditional constructor alternate constructor inflating layout传统构造函数替代构造函数膨胀布局的区别
【发布时间】:2021-05-07 12:30:18
【问题描述】:

我正在学习使用 Kotlin 进行 Android 开发。 我有一个关于扩展布局的问题。

我可以使用两种方式。传统方式:

class MainFragment : Fragment() {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    val view: View = inflater.inflate(R.layout.fragment_main, container, false);
    return view;
}

另一种方式:

class MainFragment : Fragment(R.layout.fragment_main) {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }
}

我的问题:用法有什么不同吗?我的意思是有一种情况,我必须使用一个而不是另一个,还是它们的操作相同,只是以不同的方式编写? 如果有区别,哪一种以及何时我必须更喜欢传统的充气方法以及何时使用替代方法? 也许如果有任何文章或其他内容,如果有人可以给我发一个链接,将不胜感激。

【问题讨论】:

    标签: android android-layout android-fragments layout-inflater android-inflate


    【解决方案1】:

    我会说,在 onCreateView(注意不同的覆盖)内,您通常会执行以下操作:

      override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.foo, container, false)
    }
    

    因为这是我们创建视图的地方,所以让它保持这样是有意义的,对吧?

    现在,在onViewCreated 内部:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ...
    }
    

    【讨论】:

      【解决方案2】:

      首先是onCreateView不是onViewCreated,看Fragment的代码onCreateView没有区别,如果构造函数中提供了layout_idonCreate就会inflate还给你

        @Nullable
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
             @Nullable Bundle savedInstanceState) {
               if (mContentLayoutId != 0) {
                  return inflater.inflate(mContentLayoutId, container, false);
               }
               return null;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-23
        • 1970-01-01
        • 2015-02-24
        • 2015-10-25
        • 1970-01-01
        相关资源
        最近更新 更多