简体   繁体   中英

I want to send data from fragment to fragment

I want to send data from fragment to fragment using arguments the way I am doing is mentioned below.

here's on button click data sent to fragment using argument

//sender fragment 
view.btnjavafragment.setOnClickListener {
            newInstance("helllo")
        }

  companion object {
        @JvmStatic
        fun newInstance(mystring:String) = javaFragment().apply {
            arguments = Bundle().apply {
              putString("sentdata",mystring)
              if(arguments!=null){
                  Toast.makeText(context,"data sent",Toast.LENGTH_SHORT).show()
              }
            }
        }
    }

//receiving fragment 
override fun onAttach(context: Context?) {
        super.onAttach(context)
        arguments?.getString("sentdata","")?.let {
            string = it
            tvdatamessage.setText(string)
        }
    }

Hi Please follow below link for your solutions.

https://www.journaldev.com/14207/android-passing-data-between-fragments

You can also use Navigation Graph for Fragment Transaction and directly send any kind of data in bundle to send it like below.

var nameBundle = Bundle()
nameBundle.putString("youKey", edtName.text.toString())
it.findNavController().navigate(R.id.tofragmentName, nameBundle)

It is not recommended that two Fragments should communicate directly. Check out the documentation and examples here. https://developer.android.com/training/basics/fragments/communicating

I would recommend a common ViewModel and observe the changes there.

You can use SafeArgs that are part of Navigation component on Jetpack. Here you have nice tutorial made by Google.

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