Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save anoopmaddasseri/457e4f09826b3682938853db71661dbd to your computer and use it in GitHub Desktop.
Save anoopmaddasseri/457e4f09826b3682938853db71661dbd to your computer and use it in GitHub Desktop.
Generic StartActivityForResult contract - JAVA & Kotlin
ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent intent = result.getIntent();
// Handle the Intent
}
}
});
@Override
public void onCreate(@Nullable savedInstanceState: Bundle) {
// ...
Button startButton = findViewById(R.id.start_button);
startButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// The launcher with the Intent you want to start
mStartForResult.launch(new Intent(this, ResultProducingActivity.class));
}
});
}
val startForResult = registerForActivityResult(StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
val intent = result.intent
// Handle the Intent
}
}
override fun onCreate(savedInstanceState: Bundle) {
// ...
val startButton = findViewById(R.id.start_button)
startButton.setOnClickListener {
// Use the Kotlin extension in activity-ktx
// passing it the Intent you want to start
startForResult.launch(Intent(this, ResultProducingActivity::class.java))
}
}
@nmaupu
Copy link

nmaupu commented Dec 5, 2022

OMG, thank you so much for this snippet ! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment