OnBackPressed 未调用

OnBackBressed not called

我有 activity ActivityProfile,有 getSupportActionBar().setDisplayHomeAsUpEnabled(true); 实施,还有 onBackPressed(),在互联网上搜索,仍然没有帮助。

@Override
    public void onBackPressed() {
        Toast.makeText(this, "OnBackpressed fired", Toast.LENGTH_SHORT).show();
        super.onBackPressed();
    }

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

使用设备的后退按钮可以,但不能在应用程序上使用...

您好,请在您的 activity 中添加此代码。当您在执行代码后按工具栏中的后退按钮时。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_view);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case android.R.id.home:
            finish();
            break;
        default:
            return super.onOptionsItemSelected(item);

    }
    return super.onOptionsItemSelected(item);
}

您应该使用 onOptionItemSelected 来处理点击操作栏底部的操作:

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    switch (item.getItemId())
    {
    case android.R.id.home:
        finish();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

试试这个

setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

这应该有效

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        onBackPressed();
    }

    return super.onOptionsItemSelected(item);
}

要实现向上导航,请在清单中声明该特定 activity 的父级并将 setDisplayHomeAsUpEnabled 设置为 true。

 <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>

阅读更多https://developer.android.com/training/implementing-navigation/ancestral.html