Home > Software engineering >  Is it possible to invoke a back button click programmatically?
Is it possible to invoke a back button click programmatically?

Time:11-23

I've seen plenty of answers explaining how to override and add functionality to a back button press via user's interaction, but almost none of the answers explain how to programmatically trigger a back button press without any user input. Answers that do address it give somewhat deprecated code samples that don't really compute.

CodePudding user response:

From your activity just call => onBackPressed(),

or form your fragment => activity?.onBackPressed()

CodePudding user response:

//simply put this code where you want to make back intent
super.onBackPressed();

CodePudding user response:

According to official docs onBackPressed is deprecated in Api level 33.

you can now use onBackPressedDispatcher please follow these steps:

  1. Add android:enableOnBackInvokedCallBack="true” inside application tag in manifest folder.

Kotlin code :

class YourActivity : AppCompatActivity() {

lateinit var button: Button

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

    button = findViewById(R.id.txt)
    button.setOnClickListener {
        onBackPressedCallback.handleOnBackPressed()
    }

}

private val onBackPressedCallback = object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        finish()  //this finishes the current activity
        // Your business logic to handle the back pressed event
    }

  }
}

And here is old way of implementation:

Java :

buttonBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            YourActivity.super.onBackPressed();
        }
    });

Kotlin :

 buttonBack.setOnClickListener{
        super.onBackPressed()
    }
  • Related