Home > OS >  How to Transfer Data from a Fragment to an Activity in Kotlin?
How to Transfer Data from a Fragment to an Activity in Kotlin?

Time:06-15

Basically I'm trying to change a variable in my MainActivity from a Fragment. How would I go about doing it?

CodePudding user response:

If your fragment is associated with MainActivity, you can get the fragmentActivity by using requireActivity().i.e.:
In your MainActivity:

class MainActivity : AppCompatActivity() {
  var temp = "sth"
}

Then in your Fragment, you can access the variable by

(requireActivity() as MainActivity).temp

CodePudding user response:

So basically, don't use the fragmentBinding thingy.

Always use the view.findViewByID<>(R.id.name)

then override the onCreateView function and in that function you can call (requireActivity() as MainActivity).theVariableYouWantToGet to get the variable you want.

You can also change the value of the variable in the Activity itself.

This took me wayy too long to figure out lol, hope this will help other people.

  • Related