Best practice for instantiating a new Android Fragment

前端 未结 13 1494
暖寄归人
暖寄归人 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:02

    I'm lately here. But somethings I just known that might help you a bit.

    If you are using Java, there is nothing much to change. But for kotlin developers, here is some following snippet I think that can make you a basement to run on:

    • Parent fragment:
    inline fun  newInstance(text: String): T {
        return T::class.java.newInstance().apply {
            arguments = Bundle().also { it.putString("key_text_arg", text) }
        }
    }
    
    • Normal call
    val f: SampleFragment = SampleFragment.newInstance("ABC")
    // or val f = SampleFragment.newInstance("ABC")
    
    • You can extend the parent init operation in child fragment class by:
    fun newInstance(): ChildSampleFragment {
        val child = UserProfileFragment.newInstance("XYZ")
        // Do anything with the current initialized args bundle here
        // with child.arguments = ....
        return child
    }
    
    

    Happy coding.

提交回复
热议问题