How to pass and get value from fragment and activity

前端 未结 9 1269
独厮守ぢ
独厮守ぢ 2020-12-25 11:28

How to pass and get value from fragment and activity?

9条回答
  •  情深已故
    2020-12-25 12:02

    Do it in more Kotlin style

    1) Create an inline function:

    inline fun  FRAGMENT.putArgs(argsBuilder: Bundle.() -> Unit): FRAGMENT = this.apply { arguments = Bundle().apply(argsBuilder) }
    

    2) Now you can use this extension in all fragments without duplication of code:

    class MyFragment: Fragment() {
        companion object {
            fun newInstance(name: String) = MyFragment().putArgs {
                 putString("nameKey", name)
            }
        }
    }
    
    class MyFragment1: Fragment() {
         companion object {
             fun newInstance(boolean: Boolean) = MyFragment1().putArgs {
                  putBoolean("booleanKey", boolean)
             }
         }
    }
    

    3) Create your fragments:

    val myFragment = MyFragment.newInstance("NAME")
    val myFragment1 = MyFragment1.newInstance(true)
    

提交回复
热议问题