[英]passing data from fragment to activity is not same
I have fragment in activity. 我的活动有片段。 and I want to send data from fragment to activity.
我想将数据从片段发送到活动。
how I get data in Fragment and send to my Activity: 我如何在Fragment中获取数据并发送给我的Activity:
val edit = question!!.id
(activity as QuestionActivity).kirimItem(edit)
in activity : 活动中:
fun kirimItem(item: String) {
idItem = item
}
and I call idItem in the button next onClick and show Toast the value from idItem 我在onClick旁边的按钮中调用idItem并显示Toast来自idItem的值
in the fragment, when I test data, question!!.id = 8 but toast is showing 11. The question is, why passing data from fragment to activity is not same. 在片段中,当我测试数据时,问题!!。id = 8,但吐司显示11。问题是,为什么将数据从片段传递到活动并不相同。 please guide me:(
请指导我:(
There are recommendations for passing data between activities and fragments (in a same activity). 有建议在活动和片段(在同一活动中)之间传递数据。 These are possible scenarios.
这些是可能的方案。
For 1., just use just use android.content.Intent
. 对于1.,只需使用
android.content.Intent
。 For 2., 3. and 4. scenarios, we can use android.arch.lifecycle.ViewModel
to passing data between them. 对于2.,3。和4.场景,我们可以使用
android.arch.lifecycle.ViewModel
在它们之间传递数据。 An example for 4. (Fragment -> Fragment)
is here ( https://developer.android.com/topic/libraries/architecture/viewmodel ) under topic Share data between fragments
. 示例
4. (Fragment -> Fragment)
在此处( https://developer.android.com/topic/libraries/architecture/viewmodel )下的主题Share data between fragments
。
For that example, it can be applied not only 4.
scenario but also to 2.
and 3.
as well. 对于该示例,它不仅可以应用于
4.
场景,而且还可以应用于2.
和3.
.。
I am not sure that what is the rest of our code. 我不确定其余的代码是什么。 This piece of code below works for me.
下面的这段代码对我有用。
// Fragment, `btn` is Button and `edt` is EditText
btn.setOnClickListener {
(activity as MainActivity?)?.callToast(edt.text.toString())
}
// Activity
fun callToast(str: String) {
Toast.makeText(this, str, LENGTH_SHORT).show()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.