Android onBackPressed() is not being called?
This question is already answered, but I feel to clear something here in this topic. Most comments and answeres point out to use super.onBackPressed()
and that this is the cause of the not working method onBackPressed()
. But that is not correct and important to let other beginners know. The method onBackPressed()
does not need to use super.onBackPressed()
. onBackPressed()
also works if somebody, for example, comment super.onBackPressed()
out.
As the questionier has written, he won´t use super.onBackPressed()
because it will close the activity. So, the cause of this why it isn´t working, could be seperated into three possible causes:
- The Log doesn´t work because of a wrong filter in the logcat console
- The Toast dosn´t work because of the wrong passed context
- The OS is implemented wrong by the supplier.
Usually, the toast works by passing the correct context. In the case of questioner, simply passing this
.
@Override
public void onBackPressed() {
Log.d("MainActivity","onBackPressed");
Toast.makeText(this,"onBackPressed",Toast.LENGTH_SHORT).show();
}
For the Log, simply set the correct filter on logcat.
I don´t care if somebody give downvotes now, but it must be clear for other beginners, that super.onBackPressed()
must not be used.
Anyway, the use of onKeyDown()
also is a solution.
android - onBackPressed() not working for me
Update - 19th June 2022
The below answer is outdated. We can use the navigation architecture components with toolbar so the back navigation is handled for us or you should check https://developer.android.com/guide/navigation/navigation-custom-back
For navigation architecture components check
https://developer.android.com/guide/navigation/navigation-getting-started
Navigation components are available for compose as well
https://developer.android.com/jetpack/compose/navigation
Old Answer - Outdated
I would suggest you to use ActionBar as suggested by WarrenFaith in the comments below. Pls check the link below for more information
http://developer.android.com/design/patterns/navigation.html
Here's a tutorial for the same
http://www.vogella.com/articles/AndroidActionBar/article.html
You can use this. However this also seems to be a bad design. You can check the comments below to know why
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed() {
Intent myIntent = new Intent(MyActivity.this, MainActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
finish();
return;
}
Onn back button pressed inn your current activity when you back press you clear the activity stack and naviagate to MainActivity.
Also i would suggest no to display a alert dialog on back button press. Its a bad design. You can search on SO. i read the same and was answered by commonsware
Android onBackPressed() not working
Try something from this link:
Key Events in TabActivities?
Each tab's Activity handled the "back" presses.
Why is onBackPressed() not being called?
onBackPressed()
is invoked when user clicks on a hardware back button (or on the 'up' button in the navigation bar), not the button in the action bar. For this one you need to override onOptionsItemSelected()
method. Example:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// click on 'up' button in the action bar, handle it here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
onBackPressed() method not triggered in AppCompatActivity
In your manifest file define the following inside your activity tag:
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.ParentActivity" />
After that in your activity:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Android: onBackPressed is not called when EditText is focused
EditText has it's own listener and on back pressed method that responds when the editing window is active. onBackPressed() method works when the activity itself is directly listening for clicks.
Android: onBackPressed not being recognized
You have to put it on an Activity
, don't forget to call @Override
@Override
public void onBackPressed()
{
super.onBackPressed(); //if you want to do something new remove this line
}
The problem is that you have to place the onBackPressedMethod()
outside, as follows :
public class player1 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
@Override
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
//if you want to do the back action aswell, uncomment the following line
//super.onBackPressed();
}
onActivityResult not working with onBackPressed?
You need to return the result when you press the ActionBar
back/home button, but you added the code in the bottom back button.
So, transfer the code in Activity2
to be handled when the ActionBar
back button is pressed, so Override onOptionsItemSelected
, and the home button has an id of android.R.id.home
.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Intent intent = new Intent(this, Activity1.class);
intent.putExtra("MESSAGE", "Hello from Activity 2!");
Log.i("TEST", "Setting result...");
setResult(RESULT_OK, intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Related Topics
Load Large Images with Picasso and Custom Transform Object
How to Pop Fragment Off Backstack
Android Listview Setselection() Does Not Seem to Work
Android Studio: Unable to Start the Daemon Process
Error Type 3: Activity Class {...} Does Not Exist
How to Take Multiple Photos Before Dismissing Camera Intent
Save State of Activity When Orientation Changes Android
How to Create Always-Top Fullscreen Overlay Activity in Android
How to Run Opencv Code Without Opencv Manager
Android: Rotate Image Without Loading It to Memory
How to Wrap Lengthy Text in a Spinner
Read Command Output Inside Su Process
How to Execute a Method by Clicking a Notification
How to Use Startactivityforresult() for Email Intent
How to Authenticate Two Types of Users (Student and Driver) in My Android App Using Firebase