Android 工具栏后退按钮上的动画

Animation on Android Toolbar Back Button

我有一个 activity,它有一个显示后退按钮的工具栏。

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar_about"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:title="@string/app_name"
        />

后退按钮是这样启用的:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_about);
setSupportActionBar(toolbar);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);

我从我的主 activity 中这样称呼这个 activity:

Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);

Activity 的父项已在清单中定义

<activity android:name=".AboutActivity">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".EntryActivity" />
</activity>

到目前为止一切正常,除了在使用工具栏中的后退按钮时过渡动画是错误的。

当我打开 activity 时,它从右侧滑入。

当我按下 phone 的物理后退按钮时,它再次向右滑出。这是正确的。

但是,当使用工具栏后退按钮时,它会向左滑出。这看起来不对。我该如何更改它,使其复制物理后退按钮的行为?

当您按下 Actionbar Up 按钮时,AppCompatActivity 在其 onMenuItemSelected() 调用中检测到此按钮按下,并调用 onSupportNavigateUp()。此方法确定 "parent activity" Intent 并使用它向上导航。因为它使用 Intent 来(重新)打开前一个 activity,它使用与打开 "new" 屏幕相同的动画。

假设您不关心 "Up Navigation" 模式的特殊细节(听起来您不关心,因为评论让我相信您没有横向导航而且您可以'除了你的第一个 activity 之外,你无法从任何地方到达你的第二个 activity),你可以通过覆盖 onSupportNavigateUp() 方法来回避所有这些内置的 "up" 行为。

@Override
public boolean onSupportNavigateUp() {
    finish();
    return true;
}

这意味着按下 Actionbar Up 按钮总是简单地 finish()es 你的 activity,所以(就像我之前说的)你失去了所有智能内置 "up" 行为......但你不想要那样。

您也可以在 onOptionsItemSelected() 中处理 Actionbar Up 按钮,但我更喜欢另一种方式,因为我认为您劫持系统的 up 行为更加明显。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        finish();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

有了其中任何一个,您可以从您的清单中删除 "parent" 定义,因为现在它们未被使用。

试试这个:

override fun onSupportNavigateUp(): Boolean { onBackPressed() return true }

这是因为活动的默认 launchModestandard
standard 的文档说明如下:

The system always creates a new instance of the activity in the target task and routes the intent to it.

您可以通过在 parent/starting activity 上使用 android:launchMode="singleTop" 来解决此问题。

If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity.

有关详细信息,请参阅 Tasks and the back stack and android:launchMode