The library is hosted on jCenter.
dependencies {
...
implementation 'com.afollestad:inline-activity-result:0.1.0'
}
You call startActivityForResult
, providing an Activity to launch as the generic type. You
receive the result in a callback without having to override onActivityResult
. And, you don't
have to worry about requestCode or resultCode.
class NewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val extras = Bundle()
.putString("some_extra", "Hello, World!")
startActivityForResult<OtherActivity>(extras) { success, data ->
if (success) {
toast("Got successful result!")
}
}
}
}
Well, the code speaks for itself.
class OldActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val intent = Intent(this, OtherActivity::class.java)
.putExtra("some_extra", "Hello, World!")
startActivityForResult(intent, REQUEST_CODE)
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
toast("Got successful result!")
}
}
companion object {
private const val REQUEST_CODE = 69
}
}
You do not have to override onActivityResult
at all. All of your results are received inline.
This may not seem like a big deal with the sample above, but it gets more valuable as you start to
have more than one result case to handle. And things are scoped to the callsite, which can be very nice in various
scenarios.
Note that this can all be used from within a Fragment
as well.
There are multiple variants startActivityForResult
you can use for different use cases. All of
them allow you to pass an optional requestCode
parameter, but this should generally be unnecessary.
The simplest you can get is just a generic type and the callback.
startActivityForResult<OtherActivity> { success, data ->
// Do something
}
You can provide a Bundle
of extras to the destination Activity:
val extras = Bundle()
.putString("some_extra", "Hello, World!")
startActivityForResult<OtherActivity>(extras) { success, data ->
// Do something
}
And finally, you can use a full intent. In this variant you do not provide a generic parameter.
val intent = Intent(Intent.ACTION_VIEW)
.setData("content://some-uri".toUri())
startActivityForResult(intent) { success, data ->
// Do something
}