Spi*_*pau 30
这是Android Studio提出的解决方案(当您使用文件创建空白片段 - >新建 - >片段 - >片段(空白)并检查"包含片段工厂方法"时).
把它放在你的碎片中:
class MyFragment: Fragment {
...
companion object {
@JvmStatic
fun newInstance(isMyBoolean: Boolean) = MyFragment().apply {
arguments = Bundle().apply {
putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
.apply是一个很好的技巧,可以在创建对象时设置数据,或者在这里说明:
使用
this值作为接收器调用指定的函数[block] 并返回this值.
然后在你的Activity或Fragment中:
val fragment = MyFragment.newInstance(false)
... // transaction stuff happening here
Run Code Online (Sandbox Code Playgroud)
并阅读片段中的参数,例如:
private var isMyBoolean = false
override fun onAttach(context: Context?) {
super.onAttach(context)
arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let {
isMyBoolean = it
}
}
Run Code Online (Sandbox Code Playgroud)
享受Kotlin的魔力!
NSi*_*mon 17
有一个伴侣对象(https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects)
像往常一样定义片段,并声明在Java中充当静态newInstance()等效项的伴侣:
class ViewStackListFragment : Fragment() {
companion object {
fun newInstance(position: Int): ViewStackListFragment {
val fragment = ViewStackListFragment()
val args = Bundle()
args.putInt("position", position)
fragment.setArguments(args)
return fragment
}
}
}
Run Code Online (Sandbox Code Playgroud)
简单地在Java中调用它:
val fragment = ViewStackListFragment.newInstance(4)
Run Code Online (Sandbox Code Playgroud)
使用它来发送参数以分段
fun newInstance(index: Int): MyFragment {
val f = MyFragment ()
// Pass index input as an argument.
val args = Bundle()
args.putInt("index", index)
f.setArguments(args)
return f
}
Run Code Online (Sandbox Code Playgroud)
并得到这样的论点
val args = arguments
val index = args.getInt("index", 0)
Run Code Online (Sandbox Code Playgroud)
以更 Kotlin 的风格来做
1)创建一个内联函数:
inline fun <FRAGMENT : Fragment> FRAGMENT.putArgs(argsBuilder: Bundle.() -> Unit): FRAGMENT = this.apply { arguments = Bundle().apply(argsBuilder) }
Run Code Online (Sandbox Code Playgroud)
2)现在您可以在所有片段中使用此扩展,而无需重复代码:
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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
3)创建你的片段:
val myFragment = MyFragment.newInstance("NAME")
val myFragment1 = MyFragment1.newInstance(true)
Run Code Online (Sandbox Code Playgroud)
小智 6
Kotlin,片段:用于通行证
companion object {
private const val ARGUMENT_ACTION = "ARGUMENT_ACTION"
fun newInstance(action: Int) : MyFragment{
return MyFragment().apply {
arguments = bundleOf(ARGUMENT_ACTION to action)
}
}
}
Run Code Online (Sandbox Code Playgroud)
忘记
requireArguments().getInt(ARGUMENT_ACTION)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29253 次 |
| 最近记录: |