2

I'm finding a way to move fragment to fragment by using ClickListener; but I have no idea how to move fragment to fragment.

I want move like this :

A fragment have 4 cardview

click 1 cardview : move to fragment B
click 2 cardview : move to fragment C
click 3 cardview : move to fragment D
click 4 cardview : move to fragment F

I have done fragment move to activity by using code below

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        power655Card.setOnClickListener {
            val intent = Intent (getActivity(), Power655Activity::class.java)
            getActivity()?.startActivity(intent)
        }
schlebe
  • 3,387
  • 5
  • 37
  • 50
아치귀여워
  • 21
  • 1
  • 1
  • 2
  • 1
    Can you please explain which fragment you move to. You explain that you move something TO a fragment; but which fragment is moving when you click on 1cardview ? – schlebe May 22 '20 at 06:24
  • Are you asking how to navigate between fragments? – Sina May 22 '20 at 09:30
  • Does this answer your question? [How to use Fragments in Android](https://stackoverflow.com/questions/16033602/how-to-use-fragments-in-android) – Sina May 22 '20 at 09:37

4 Answers4

9

In Kotlin, if you want to load various fragment inside activity, you can make one function which you call wherever required to load the fragment.

private fun loadFragment(fragment: Fragment){
    val transaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.fl_main, fragment)
    transaction.disallowAddToBackStack()
    transaction.commit()
}

And if you want to load fragment from a fragment,

    val transaction = activity.supportFragmentManager.beginTransaction()
    transaction.replace(R.id.fl_main, SecondFragment())
    transaction.disallowAddToBackStack()
    transaction.commit()

In the above code spinnet, SecondFragment() is the instance of the fragment which you wish to load. So we can also pass the instance of the fragment as shown above.

hetsgandhi
  • 726
  • 3
  • 9
  • 25
2

You can use requireActivity().supportFragmentManager.beginTransaction() to make the fragments transactions you need to.

0

You can change fragment putting this in you listener:

val fragmentB = FragmentB()
activity.getSupportFragmentManager().beginTransaction()
             .replace(R.id.layout_container, fragmentB, "fragmnetId")
             .commit();

R.id.layout_container is the fragment container in you activity xml

fragmentId is the id of the fragment so you can refer to it later.

Joan
  • 321
  • 1
  • 10
0
val fragmentB =FragmentB()
activity?.getSupportFragmentManager()?.beginTransaction()?.replace(R.id.layout_container, fragmentB, "fragmnetId")?.commit();
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129