Android: Clear the back stack

前端 未结 30 2206
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 06:47

In Android I have some activities, let\'s say A, B, C.

In A, I use this code to open B:

Intent intent = new Intent(this, B.class);
startActivity(inte         


        
30条回答
  •  无人共我
    2020-11-22 07:25

    Advanced, Reuseable Kotlin:

    You can set the flag directly using setter method. In Kotlin or is the replacement for the Java bitwise or |.

    intent.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK
    

    If use this more than once, create an Intent extension function

    fun Intent.clearStack() {
        flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
    }
    

    You can then directly call this function before starting the intent

    intent.clearStack()
    

    If you need the option to add additional flags in other situations, add an optional param to the extension function.

    fun Intent.clearStack(additionalFlags: Int = 0) {
        flags = additionalFlags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
    }
    

提交回复
热议问题