Do we have to use the same method for sharing data from one fragment to another?
And every time I’m running the app, the argument is not receiving the actual value being sent from the activity. Every time it is taking the default value.
Do we have to use the same method for sharing data from one fragment to another?
And every time I’m running the app, the argument is not receiving the actual value being sent from the activity. Every time it is taking the default value.
Could you share your code for the same?
First Fragment:
package com.example.slidingfragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment_first.*
import kotlinx.android.synthetic.main.fragment_first.view.*
class FirstFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_first, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.btn.setOnClickListener {
Toast.makeText(requireContext(),"Name is ${etName.text}",Toast.LENGTH_SHORT).show()
// to send some data to other fragment
val bundle = Bundle()
bundle.putString("KEY","Apoorv Srivastava")
val fragment = SecondFragment()
fragment.arguments = bundle
}
}
}
Second Fragment:
package com.example.slidingfragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_second.*
class SecondFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_second, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// To receive data sent by some other fragment/ activity
val name: String? = arguments?.getString(“KEY”) ?: “Default value”
textView.setText(name)
}
}
I can only see that you have created the object of fragment what about adding or replacing the fragment ?