简体   繁体   English

FLAG_ACTIVITY_SINGLE_TOP 不适用于 startActivityForResult

[英]FLAG_ACTIVITY_SINGLE_TOP not working with startActivityForResult

Is there a way to prevent multiple instances of an activity from being created with startActivityForResult ?有没有办法防止使用startActivityForResult创建活动的多个实例?

For example:例如:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<TextView>(R.id.button).setOnClickListener {
            startActivityForResult(Intent(this, MainActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
            }, 1)
        }
    }
}

Clicking on the button multiple times opens multiple instances of the MainActivity even though I've set FLAG_ACTIVITY_SINGLE_TOP多次单击按钮会打开MainActivity的多个实例,即使我已经设置了FLAG_ACTIVITY_SINGLE_TOP

Edit: Looks like there's a difference in behaviour depending on what Android version I'm running on.编辑:看起来行为有所不同,具体取决于我运行的 Android 版本。 Android 8 opens a new Activity but Android 13 does not open a new Activity. Android 8 打开一个新的Activity 但Android 13 没有打开一个新的Activity。 How do I ensure that all android versions have the Android 13 behaviour?我如何确保所有 android 版本都具有 Android 13 行为?

you can add android:launchMode="singleTop" in the manifest of your activity.您可以在活动清单中添加 android:launchMode="singleTop"。

android:name=".ui.activity.MainActivity"
android:exported="false"
android:screenOrientation="portrait"
android:launchMode="singleTop"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM