如何从碎片和活动中传递价值并获得价值 [英] How to pass and get value from fragment and activity
问题描述
如何通过片段和活动获得价值?
How to pass and get value from fragment and activity?
推荐答案
这是Android Studio建议的解决方案(=当您使用文件创建Blank-Fragment-> New-> Fragment-> Fragment(Blank)并检查包括片段工厂方法").
Here is the Android Studio proposed solution (= when you create a Blank-Fragment with File -> New -> Fragment -> Fragment(Blank) and you check "include fragment factory methods").
将其放入片段中
class MyFragment: Fragment {
...
companion object {
@JvmStatic
fun newInstance(isMyBoolean: Boolean) = MyFragment().apply {
arguments = Bundle().apply {
putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean)
}
}
}
}
.apply
is a nice trick to set data when an object is created, or as they state here:
以
this
值作为接收者调用指定的函数[block] 并返回this
值.
Calls the specified function [block] with
this
value as its receiver and returnsthis
value.
然后在活动"或片段"中执行以下操作:
Then in your Activity or Fragment do:
val fragment = MyFragment.newInstance(false)
... // transaction stuff happening here
并读取片段中的参数,例如:
and read the Arguments in your Fragment such as:
private var isMyBoolean = false
override fun onAttach(context: Context?) {
super.onAttach(context)
arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let {
isMyBoolean = it
}
}
享受科特林的魔力!
这篇关于如何从碎片和活动中传递价值并获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!