Java 如何在Android上为ActionBar中的up按钮添加侦听器?

Java 如何在Android上为ActionBar中的up按钮添加侦听器?,java,android,android-actionbar,Java,Android,Android Actionbar,我在android活动的操作栏中添加了向上按钮,如下所示: 活动: getSupportActionBar().setDisplayHomeAsUpEnabled(true) 舱单: android:parentActivityName=“.MenuActivity”> 它工作得很好,但现在我想在活动之间添加一个过渡效果。 这种过渡很有效: Intent Intent=新的Intent(getApplicationContext(),MenuActivity.class); 星触觉(意向); 覆

我在android活动的操作栏中添加了向上按钮,如下所示:

活动:

getSupportActionBar().setDisplayHomeAsUpEnabled(true)

舱单:

android:parentActivityName=“.MenuActivity”>

它工作得很好,但现在我想在活动之间添加一个过渡效果。 这种过渡很有效:

Intent Intent=新的Intent(getApplicationContext(),MenuActivity.class); 星触觉(意向); 覆盖转换(R.anim.slide\u in\u left,R.anim.slide\u out\u right)

但是我应该把这个转换代码放在哪里?操作栏中的“后退”按钮没有任何侦听器。


感谢大家的建议

在命令setSupportActionBar(工具栏)之后添加此命令


操作栏中的“向上”按钮被视为ID为android.R.ID.home的菜单项,您可以在中阅读。在那里,您可以发现您可以使用以下代码处理对它的单击:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        // Respond to the action bar's Up/Home button
        return false;
    }
    return super.onOptionsItemSelected(item);
}

如果操作栏中有后退按钮,则必须在menu.xml文件中定义。因此,我们必须在java文件中添加该按钮的侦听器

下面是menu.xml的外观:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.sknandroidapps.skn.ptternlock.LockScreen">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />
将此应用于您的代码,并让我知道它是否有效

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.sknandroidapps.skn.ptternlock.LockScreen">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    noinspection SimplifiableIfStatement
       if (id == R.id.action_settings) {
         //here you have to put the transiction code.
         return true;
       }

    return super.onOptionsItemSelected(item);
}