Android 在工具栏上显示后退箭头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26651602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 12:01:43  来源:igfitidea点击:

Display Back Arrow on Toolbar

androidandroid-actionbarandroid-actionbar-compatandroid-toolbar

提问by Huy Duong Tu

I'm migrating from ActionBarto Toolbarin my application. But I don't know how to display and set click event on Back Arrow on Toolbarlike I did on Actionbar.

我正在我的应用程序中从 迁移ActionBarToolbar。但我不知道如何Toolbar像我在Actionbar.

enter image description here

在此处输入图片说明

With ActionBar, I call mActionbar.setDisplayHomeAsUpEnabled(true). But there is no the similar method like this.

随着ActionBar,我打电话mActionbar.setDisplayHomeAsUpEnabled(true)。但没有类似的方法。

Has anyone ever faced this situation and somehow found a way to solve it?

有没有人遇到过这种情况并以某种方式找到解决方法?

回答by MrEngineer13

If you are using an ActionBarActivitythen you can tell Android to use the Toolbaras the ActionBarlike so:

如果您使用的是ActionBarActivity,你可以告诉Android的使用Toolbar作为ActionBar像这样:

Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);

And then calls to

然后调用

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);

will work. You can also use that in Fragments that are attached to ActionBarActivitiesyou can use it like this:

将工作。您还可以在附加到的 Fragment 中ActionBarActivities使用它,您可以像这样使用它:

((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);

If you are not using ActionBarActivitiesor if you want to get the back arrow on a Toolbarthat's not set as your SupportActionBarthen you can use the following:

如果您不使用ActionBarActivities或者如果您想在Toolbar未设置为您的位置上获得后退箭头,SupportActionBar则可以使用以下内容:

mActionBar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_action_back));
mActionBar.setNavigationOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
       //What to do on back clicked
   }
});

If you are using android.support.v7.widget.Toolbar, then you should add the following code to your AppCompatActivity:

如果您正在使用android.support.v7.widget.Toolbar,那么您应该将以下代码添加到您的AppCompatActivity

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

回答by Vasil Valchev

I see a lot of answers but here is mine which is not mentioned before. It works from API 8+.

我看到很多答案,但这是我之前没有提到的。它从 API 8+ 开始工作。

public class DetailActivity extends AppCompatActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);

    // toolbar
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // add back arrow to toolbar
    if (getSupportActionBar() != null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // handle arrow click here
    if (item.getItemId() == android.R.id.home) {
        finish(); // close this activity and return to preview activity (if there is any)
    }

    return super.onOptionsItemSelected(item);
}

回答by Igor Bubelov

There are many ways to achieve that, here is my favorite:

有很多方法可以实现这一点,这是我最喜欢的:

Layout:

布局:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:navigationIcon="?attr/homeAsUpIndicator" />

Activity:

活动:

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // back button pressed
        }
    });

回答by Sam

you can use the tool bar setNavigationIcon method. Android Doc

您可以使用工具栏 setNavigationIcon 方法。 安卓文档

mToolBar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);

mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        handleOnBackPress();
    }
});

回答by Phan Van Linh

If you don't want to create a custom Toolbar, you can do like this

如果你不想创建自定义Toolbar,你可以这样做

public class GalleryActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...  
        getSupportActionBar().setTitle("Select Image");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

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

In you AndroidManifest.xml

在你 AndroidManifest.xml

<activity
    android:name=".GalleryActivity"
    android:theme="@style/Theme.AppCompat.Light">        
</activity>

you can also put this android:theme="@style/Theme.AppCompat.Light"to <aplication>tag, for apply to all activities

你也可以把这个android:theme="@style/Theme.AppCompat.Light"<aplication>标记,适用于所有活动

enter image description here

在此处输入图片说明

回答by Ilya Gazman

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setNavigationIcon(R.drawable.back_arrow); // your drawable
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed(); // Implemented by activity
        }
    });

And for API 21+ android:navigationIcon

对于 API 21+ android:navigationIcon

<android.support.v7.widget.Toolbar
    android:navigationIcon="@drawable/back_arrow"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"/>

回答by Paolo Anghileri

I used this method from the Google Developer Documentation:

我使用了Google Developer Documentation 中的这种方法:

@Override
public void onCreate(Bundle savedInstanceState) {
  ...
  getActionBar().setDisplayHomeAsUpEnabled(true);
}

If you get a null pointer exception it could depend on the theme. Try using a different theme in the manifest or use this alternatively:

如果您收到空指针异常,则可能取决于主题。尝试在清单中使用不同的主题或使用它:

@Override
public void onCreate(Bundle savedInstanceState) {
  ...
  getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

Then in the manifest, where I set the parent activity for current activity:

然后在清单中,我为当前活动设置了父活动:

<activity
        android:name="com.example.myapp.MyCurrentActivity"
        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.myapp.MyMainActivity" />
</activity>

I hope this will help you!

我希望这能帮到您!

回答by Dhiraj Gupta

If you wereusing AppCompatActivityand have gone down the path of not using it, because you wanted to not get the automatic ActionBarthat it provides, because you want to separate out the Toolbar, because of your Material Design needs and CoordinatorLayoutor AppBarLayout, then, consider this:

如果您正在使用AppCompatActivity并且已经走上了不使用它的道路,因为您不想获得ActionBar它提供的自动功能,因为您想分离Toolbar,因为您的 Material Design 需要 and CoordinatorLayoutor AppBarLayout,那么,请考虑:

You can still use the AppCompatActivity, you don't need to stop using it just so that you can use a <android.support.v7.widget.Toolbar>in your xml. Just turn off the action bar styleas follows:

您仍然可以使用AppCompatActivity,您不需要停止使用它,以便您可以<android.support.v7.widget.Toolbar>在 xml 中使用 a 。只需关闭操作栏样式,如下所示:

First, derive a style from one of the NoActionBar themes that you like in your styles.xml, I used Theme.AppCompat.Light.NoActionBarlike so:

首先,从您喜欢的 NoActionBar 主题之一派生一种样式styles.xml,我Theme.AppCompat.Light.NoActionBar是这样使用的:

<style name="SuperCoolAppBarActivity" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primary</item>

    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">@color/primary_dark</item>
    ...
    ...
</style>

In your App's manifest, choose the child style theme you just defined, like so:

在您的应用清单中,选择您刚刚定义的子样式主题,如下所示:

    <activity
        android:name=".activity.YourSuperCoolActivity"
        android:label="@string/super_cool"
        android:theme="@style/SuperCoolAppBarActivity">
    </activity>

In your Activity Xml, if the toolbar is defined like so:

在您的 Activity Xml 中,如果工具栏是这样定义的:

...
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        />
...

Then, and this is the important part, you setthe support Action bar to the AppCompatActivity that you're extending, so that the toolbar in your xml, becomesthe action bar. I feel that this is a better way, because you can simply do the many things that ActionBar allows, like menus, automatic activity title, item selection handling, etc. without resorting to adding custom click handlers, etc.

然后,这是重要的部分,您支持操作栏设置为您正在扩展的 AppCompatActivity,以便您的 xml 中的工具栏成为操作栏。我觉得这是一个更好的方法,因为你可以简单地做许多 ActionBar 允许的事情,比如菜单、自动活动标题、项目选择处理等,而无需求助于添加自定义点击处理程序等。

In your Activity's onCreate override, do the following:

在您的 Activity 的 onCreate 覆盖中,执行以下操作:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_super_cool);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(toolbar);
    //Your toolbar is now an action bar and you can use it like you always do, for example:
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} 

回答by Artemiy

MyActivity extends AppCompatActivity {

    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        toolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(arrow -> onBackPressed());
    }

回答by gprathour

In Kotlin it would be

在 Kotlin 中,它将是

private fun setupToolbar(){
    toolbar.title = getString(R.string.YOUR_TITLE)
    setSupportActionBar(toolbar)
    supportActionBar?.setDisplayHomeAsUpEnabled(true)
    supportActionBar?.setDisplayShowHomeEnabled(true)
}

// don't forget click listener for back button
override fun onSupportNavigateUp(): Boolean {
    onBackPressed()
    return true
}