Best practice for instantiating a new Android Fragment

前端 未结 13 1478
暖寄归人
暖寄归人 2020-11-21 04:38

I have seen two general practices to instantiate a new Fragment in an application:

Fragment newFragment = new MyFragment();

and

<         


        
13条回答
  •  死守一世寂寞
    2020-11-21 05:04

    Some kotlin code:

    companion object {
        fun newInstance(first: String, second: String) : SampleFragment {
            return SampleFragment().apply {
                arguments = Bundle().apply {
                    putString("firstString", first)
                    putString("secondString", second)
                }
            }
        }
    }
    

    And you can get arguments with this:

    val first: String by lazy { arguments?.getString("firstString") ?: "default"}
    val second: String by lazy { arguments?.getString("secondString") ?: "default"}
    

提交回复
热议问题