简体   繁体   中英

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:

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

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. please guide me:(

There are recommendations for passing data between activities and fragments (in a same activity). These are possible scenarios.

  1. (Activity -> Activity)
  2. (Activity -> Fragment)
  3. (Fragment -> Activity)
  4. (Fragment -> Fragment)

For 1., just use just use android.content.Intent . For 2., 3. and 4. scenarios, we can use android.arch.lifecycle.ViewModel to passing data between them. An example for 4. (Fragment -> Fragment) is here ( https://developer.android.com/topic/libraries/architecture/viewmodel ) under topic Share data between fragments .

For that example, it can be applied not only 4. scenario but also to 2. and 3. as well.

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM