在工具栏上显示后退箭头 [英] Display Back Arrow on Toolbar
问题描述
我正在从应用程序中的ActionBar
迁移到Toolbar
.
但是我不知道如何像在Actionbar
上那样显示和设置Toolbar
上的后退箭头上的click事件.
I'm migrating from ActionBar
to Toolbar
in my application.
But I don't know how to display and set click event on Back Arrow on Toolbar
like I did on Actionbar
.
使用ActionBar
,我呼叫mActionbar.setDisplayHomeAsUpEnabled(true)
.
但是没有类似的方法.
With ActionBar
, I call mActionbar.setDisplayHomeAsUpEnabled(true)
.
But there is no the similar method like this.
有没有人遇到过这种情况,并且以某种方式找到了解决方法?
Has anyone ever faced this situation and somehow found a way to solve it?
推荐答案
如果您使用的是ActionBarActivity
,则可以告诉Android将Toolbar
用作ActionBar
,如下所示:
If you are using an ActionBarActivity
then you can tell Android to use the Toolbar
as the ActionBar
like so:
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
然后调用
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
将起作用.您还可以在ActionBarActivities
附带的片段中使用它,您可以像这样使用它:
will work. You can also use that in Fragments that are attached to ActionBarActivities
you can use it like this:
((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
如果您不使用ActionBarActivities
,或者要获取未设置为SupportActionBar
的Toolbar
上的后退箭头,则可以使用以下命令:
If you are not using ActionBarActivities
or if you want to get the back arrow on a Toolbar
that's not set as your SupportActionBar
then you can use the following:
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
}
});
如果使用的是android.support.v7.widget.Toolbar
,则应将以下代码添加到AppCompatActivity
:
If you are using android.support.v7.widget.Toolbar
, then you should add the following code to your AppCompatActivity
:
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
这篇关于在工具栏上显示后退箭头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!