如何在操作栏/工具栏中添加返回按钮

4
我已经为应用程序编写了一段代码,其中我想在操作栏/工具栏上实现一个返回按钮,使得当按钮被按下时,之前的页面(即当前页面/片段之前的页面/片段)将被显示。
这是ToolBar、DrawerLayout、NavigationView和getSupportActionBar()的代码:
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setVisibility(View.VISIBLE);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

我无法使用ActionBar。由于某些原因(我不知道为什么),我的Android Studio/程序不允许我使用ActionBar。因此,我使用set/getSupportActionBar()来替代它。

与此相关的函数包括:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
     MenuInflater inflater = getMenuInflater();
     inflater.inflate(R.menu.menu_settings, menu);
     return true;
}        

@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.

     int id = item.getItemId();

     switch (id) {
         case android.R.id.home:
             onBackPressed();
             return true;
         default:
             return super.onOptionsItemSelected(item);
         }
    }        

@Override
public void onBackPressed() {

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();        
    }
}

我的activity_main.xml文件如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:id="@+id/activity_main"
    android:orientation="vertical"
    tools:openDrawer="start"
    tools:context="com.example.albin.settings_menu.SettingsActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff">

    <android.support.v7.widget.Toolbar
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:title="Settings"/>

    <android.support.v4.widget.DrawerLayout
            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"
            android:id="@+id/drawer_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <FrameLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolbar">

        </FrameLayout>

            <android.support.design.widget.NavigationView
                xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:id="@+id/nav_view"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="start"
                android:fitsSystemWindows="true"
                android:layout_marginTop="-24dp"
                app:menu="@menu/options_menu" />


        </android.support.v4.widget.DrawerLayout>

    </RelativeLayout>
    </LinearLayout>

问题是我不知道哪些代码有用,哪些没有用以及如何混合/连接/(添加额外的代码)来获得所需的结果,即在操作栏/工具栏上应用“返回”按钮。
大多数上面的代码是为“向上”按钮实现的,而不是“返回”按钮。我已经在网上和这个站点上阅读了几篇文章,但是它们都没有我所需要的内容。
希望有人能给我一个清晰的答案…
6个回答

9
您可以在ToolBar中包含返回图标:
初始化ToolBar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
  • You can use an drawable icon as a back button.

    toolbar.setNavigationIcon(R.drawable.your_drawable_icon);
    
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // what do you want here
        }
    });
    
  • If you do not want to use drawable icon then:

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // what do you want here
        }
    });
    

如果在支持操作栏中有多个视图,并且单击该图标会发生什么?我认为您需要在onClick方法中指定被单击的视图。 - FabioR

2

实际上,您的布局存在该问题,因为您在 RelativeLayout 中添加了工具栏,所以抽屉布局会重叠在其上,这就是为什么您无法单击返回箭头的原因。我已经修复了您的布局,请参见下文:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        app:navigationIcon="@drawable/ic_back_black"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:title="Settings" />

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <FrameLayout
            android:id="@+id/frame"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/toolbar" />

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:menu="@menu/options_menu" />
    </android.support.v4.widget.DrawerLayout>
</LinearLayout>

1
最简单的方法是按照开发人员文档建议,在清单文件中添加父活动。
 <activity 
    android:name=".ChildActivity"
    android:parentActivityName=".ParentActivity" >

你已经完成了Java代码,需要设置setSupportActionbar和setHomeAsUpEnabled。

编辑:必须添加图标操作才能使其可见,如Android Developer Docs中所述。


1
这并不是真的,至少当你使用CollapsingToolbarLayout时。 在清单文件中添加android: parentActivityName =“activityParentName”不会显示返回箭头按钮,但如果您添加getSupportActionBar()。setDisplayHomeAsUpEnabled(true); getSupportActionBar()。setDisplayShowHomeEnabled(true); 会出现。 - Emmanuelguther
1
@EmmanuelGuther 谢谢您的信息,您是正确的,我已经编辑了我的答案。 - geniushkg

0

因此,工具栏为Android中的标题栏提供了额外的灵活性。

至于为什么getActionBar不起作用,而你被迫使用getSupportActionBar是因为你必须使用SupportLibrary。 SupportLibrary为早期SDK版本提供了向后兼容性。

如果您想广泛修改标题栏/头部/操作栏,则使用工具栏;否则,请使用操作栏。


0

如果您正在引用来自操作栏的某些操作,例如保存操作或共享操作,并且您正在覆盖onOptionsItemSelected方法,则需要定义在单击返回主页按钮时的行为:

@Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.action_save:
        //save stuff
      break;

      //this is what you need to add to reference again back/home button
      case android.R.id.home:
        //do your stuff here, usually back to the home or close the current activity
        getActivity().finish();
      break;

      default:
      break;
    }
    return true;

0
将一个导航点击监听器添加到您的工具栏中,如下所示:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接