Steve2955
Steve2955

Reputation: 690

Android onBackPressed() is not being called?

in my MainActivity, which extends from AppCompatActivity, I want to override the onBackPressed method like so:

@Override
public void onBackPressed() {
    Log.d("MainActivity","onBackPressed");
    Toast.makeText(getApplicationContext(),"onBackPressed",Toast.LENGTH_SHORT).show();
}

but onBackPressed does not get called. How ever if I do not override onBackPressed, the application closes, when I press the backbutton and if I do override it it doesn't.

The rest of my activity looks like this:

public class MainActivity extends AppCompatActivity {

private Toolbar toolbar;
private Drawer drawer;
private FloatingActionButton fab_test;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    fab_test = (FloatingActionButton) findViewById(R.id.fab_test);
    fab_test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplicationContext(),"FAB Test pressed",Toast.LENGTH_SHORT).show();
        }
    });

    buildDrawer();

    getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer,page).commit();
}

@Override
public void onBackPressed() {
    Log.d("MainActivity","onBackPressed");
    Toast.makeText(getApplicationContext(),"onBackPressed",Toast.LENGTH_SHORT).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);      
    return true;
}
}

EDIT: I'm talking about the hardware-backbutton(not the actionbar one)

Upvotes: 23

Views: 37394

Answers (8)

Pratyush Kumar
Pratyush Kumar

Reputation: 1

if u want to use onBackpressed and added some logic to finish the activity do not use super.onBackPressed

override fun onBackPressed() {
    

    if (session!!.backControl == "onBack") {
        session!!.backControl = "offBack"
        callFragment(AdminAssetFragment())
    } else if (session!!.backControlAmenities == "onBackAmenity") {
        session!!.backControlAmenities = "offBackAmenity"
        callFragment(AdminAmenityFragment())

    } else {
        finish()
    }
}

Upvotes: 0

Chris Baaijens
Chris Baaijens

Reputation: 87

For whoever is wondering, as most functionality is deprected API 30>, the following will surely help you a lot.

public class MainActivity extends AppCompatActivity {
private OnBackPressedCallback onBackPressedCallback;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    onBackPressedCallback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            // Your business logic to handle the back pressed event
            Log.d(TAG, "onBackPressedCallback: handleOnBackPressed");
        }
    };

    getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
}
}

Upvotes: 4

amra ram
amra ram

Reputation: 81

working fine onKeyDown function return type false;

@Override

public boolean onKeyDown(int keyCode, KeyEvent event) {
  

    return false;

}

Upvotes: 0

BitByteDog
BitByteDog

Reputation: 3524

The onBackPressed() is a default action called from onKeyDown() in API < 5 and a default action called from onKeyUp() from API level 5 and up. If onKeyUp() does not call super.onKeyUp(), onBackPressed() will not be called.

Documentation onKeyDown()

Documentation onKeyUp().

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    /*
     * without call to super onBackPress() will not be called when
     * keyCode == KeyEvent.KEYCODE_BACK
     */
    return super.onKeyUp(keyCode, event);
}

Also another reason that onBackPressed() may not be called is because you are using the soft back button on the actionbar, it that case the following is needed:

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Upvotes: 23

Ahmed Esameddeen
Ahmed Esameddeen

Reputation: 89

make sure you are not calling onkeydown in your super view as it handles the back button clicking first.

Upvotes: 0

vijay
vijay

Reputation: 1495

Just Remove super.onBackPressed() it will work

Upvotes: -1

Opiatefuchs
Opiatefuchs

Reputation: 9870

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:

  1. The Log doesn´t work because of a wrong filter in the logcat console
  2. The Toast dosn´t work because of the wrong passed context
  3. 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.

Upvotes: 29

Saveen
Saveen

Reputation: 4220

You are missing, super.onBackPressed();

@Override
public void onBackPressed() {
    super.onBackPressed();
}

or you can use

@Override  
public boolean onKeyDown(int keyCode, KeyEvent event)  
{  
     //replaces the default 'Back' button action  
     if(keyCode==KeyEvent.KEYCODE_BACK)   {  
// something here
            finish();
     }  
     return true;  
 }  

thanks

Upvotes: 6

Related Questions