Last active
December 5, 2022 22:13
-
-
Save anoopmaddasseri/457e4f09826b3682938853db71661dbd to your computer and use it in GitHub Desktop.
Generic StartActivityForResult contract - JAVA & Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OMG, thank you so much for this snippet ! 👍