onBackPressed() method not triggered in AppCompatActivity

时间:2015-07-28 15:42:28

标签: android

AppCompatActivity onBackPressed() method fails to trigger in my activity.

I see the back arrow button and get the animation when pressing it, but nothing else happens. also overriding onKeyDown() has the same effect. it's not called.

I've spent many hours researching this with no luck. Nothing seems to work. Anyone has had a similar issue? Maybe this is a known bug?

My Activity.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.litenote.android.BackTestingActivity2Activity">
<include
    android:id="@+id/appBar"
    layout="@layout/app_bar" />
<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

app_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/appBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/primary"
android:titleTextAppearance="@color/textWhite"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
android:popupTheme="@style/CustomPopupMenuTheme">

The activity Java file

package com.litenote.android;

import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;

import com.superpad.android.R;

public class BackTestingActivity2Activity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_back_testing_activity2);
    Toolbar actionBar = ((Toolbar) findViewById(R.id.appBar));
    setSupportActionBar(actionBar);
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

}

@Override
public void onBackPressed() {
    Log.d("BACK_BUTTON_DOESNT_WORK", "I will never execute and you will never see me :(");
    super.onBackPressed();
    this.finish();
}
}

6 个答案:

答案 0 :(得分:6)

I believe onBackPressed() is only called when the physical back button is pressed. If you're attempting to catch the toolbar back button press (the navigation icon), try using the following snippet:

@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
    switch (menuItem.getItemId()) {
        case android.R.id.home: {
            // Your code here
        }
    }
    return (super.onOptionsItemSelected(menuItem));
}

答案 1 :(得分:3)

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);
        }
    }

答案 2 :(得分:3)

操作栏上的

back_button

这将会发生

Toolbar toolbar=(Toolbar) findViewById(R.id.appBar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP);
getSupportActionBar().setDisplayShowHomeEnabled(true);

@Override
public void onBackPressed() {
super.onBackPressed();
this.finish();

}

设置点击返回时的活动负载

<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.ParentActivity" />

答案 3 :(得分:1)

AppCompactActivity 中不存在

onBackPressed(), 您必须实现 InterFace KeyEvent.Callback 并覆盖 onKeyUp方法并检查密钥是否为BackButton,或者您可以扩展 ActionBarActivity < / strong>这是 AppCompactActivity 的子类

答案 4 :(得分:0)

This code works for me. Obviously there isn't all the code, but i think it can usefull for you to understand how to implements the backPressed event.

public class RedActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    ...
    final ActionBar ab = getSupportActionBar();
    ab.setHomeAsUpIndicator(R.drawable.ic_menu);
    ab.setDisplayHomeAsUpEnabled(true);
    ...
  }

  ...

  @Override
  public void onBackPressed() {
    if (isDrawerOpen()) {
      drawerLayout.closeDrawer(GravityCompat.START);
    } else if (getFragmentManager().getBackStackEntryCount() > 0) {
      getFragmentManager().popBackStack();
    } else {
     //Ask the user if they want to quit
     new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle(R.string.quit)
                        .setMessage(R.string.really_quit)
                        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {        
                                finish();
                            }

                        })
          .setNegativeButton(R.string.no, null)
          .show();
       }
    }
}

答案 5 :(得分:-1)

这就是您需要添加的内容

@Override
    public void onBackPressed() {
        finish();
    }