Basically I have a MainActivity which contains 3 different fragments, and within one of those fragments I can click a button that opens a new activity with a simple RadioGroup choice, and whenever I click on one of the options, it automatically closes the activity. Now, my problem is transfering that selected data to the fragment, so I can update it depending on which RadioButton I chose.
The closest I have come to a solution for this is startActivityForResult, but it seems that is no longer working...
CodePudding user response:
You can use SharedPreferences to save the state of the radio buttons, or you can create a callback function that triggers the main activity when you dispose the fragment and pass as parameter the state of the radio buttons.
CodePudding user response:
From official guide doc:
In your fragment, create & register a launcher
private val launcher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result: ActivityResult ->
handleResult(result)
}
Create a method to handle ActivityResult:
fun handleResult(result: ActivityResult) {
// Handle the returned result as you do in onActivityResult()
// Use result.resultCode to determine OK or Cancelled result
if (result.resultCode == Activity.RESULT_OK) {
val resultIntent = result.data
// Use returned Intent
}
}
Launch the OtherActivity for result like this:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// ...
val selectButton = findViewById<Button>(R.id.select_button)
selectButton.setOnClickListener {
// Launch activity from whom you want the result
val intent = Intent(requireContext(), OtherActivity::class.java)
launcher.launch(intent)
}
}
In the OtherActivity, when you're ready to send back result, create an intent and put the data in it.
val intent = Intent()
intent.putExtra("YOUR_KEY", YOUR_DATA_HERE)
setResult(Activity.RESULT_OK, intent)
finish()
After this, you will get result in handleResult() method.
