skip to Main Content

I just start to learn how to use Android studio for a while and my teacher asks me the question above with many require. But I don’t even get the concept to get and pass the data. Hope someone can tell me the concept with some coding.

2

Answers


  1. In case both fragments display on activity, you should use viewmodel, this is link for more infor and has code sample pass data via viewModel document . With other cases, you can use bundle to transfer data.

    Login or Signup to reply.
  2. You can choose FragmentResult API or viewModel. It depends on the nature of the data you want to pass. If it is just a simple "result", like your fragment A want to know you click which button in fragment B, the FragmentResult is enough. If you need to share data between A and B, viewModel is better.

    FragmentResult:

    fragment A

    setFragmentResultListener("requestKey") { requestKey, bundle ->
        // We use a String here, but any type that can be put in a Bundle is supported
        val result = bundle.getString("bundleKey")
        // Do something with the result
    }
    

    fragment B

    button.setOnClickListener {
        val result = "result"
        // Use the Kotlin extension in the fragment-ktx artifact
        setFragmentResult("requestKey", bundleOf("bundleKey" to result))
    }
    

    Here is the doc

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search