如何在Kotlin的一行中声明startActivityforResult()?

时间:2018-05-31 05:58:56

标签: kotlin

我想在Kotlin的一行声明中呼叫startActivityforResult。像这样:

startActivityForResult(Intent(this@MainActivity2,MainActivity::class.java),1))

2 个答案:

答案 0 :(得分:8)

选项1:使用Anko库:

startActivityForResult<MainActivity>(1)

选项2:您可以在Activity或AppCompactActivity上创建自己的扩展功能:

inline fun <reified T: Activity> Activity.myStartActivityForResult(requestCode: Int) {
    val intent = Intent(this, T::class.java)
    startActivityForResult(intent, requestCode)
}

myStartActivityForResult<MainActivity>(1)

答案 1 :(得分:0)

这是对startActivityForResult进行一行调用的一种干净方法。在结果活动中,您将必须创建一个随播对象以设置启动意图。

活动

class MyActivity {
    companion object {
        const val CONTACT_REQUEST = 1
    }

    fun activityCall() {
        startActivityForResult(MyActivity.getLaunchIntent(this), CONTACT_REQUEST)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // Check which request we're responding to
        if (requestCode == MyActivity.CARD_CONTACT_REQUEST) {
            // Make sure the request was successful
            if (resultCode == Activity.RESULT_OK) {
                // The user picked a contact.
                // The Intent's data Uri identifies which contact was selected.

                // Do something with the contact here (bigger example below)
            }
        }
    }
}

结果类

class MyResultActivity {
    companion object {
        fun getLaunchIntent(context: Context): Intent {
            val intent = Intent(context, MyActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            return intent
        }
    }
}