简体   繁体   English

如何在导航栏中创建后退按钮的片段?

[英]how to create back button in navigation bar in a fragment?

I want to create a back navigation button that will take me back to the fragment before it when pressed. 我想创建一个后退导航按钮,按下该按钮将使我回到片段之前。 I looked at so many questions asked here but none of them help my needs. 我看着这里问了这么多问题,但没有一个能满足我的需求。 If anyone here know something or have an idea on how to do this please direct me or at least show me how to do it. 如果这里有人知道如何执行此操作,或者对如何执行操作有任何想法,请指导我或至少告诉我如何操作。 I really appreciate it. 我真的很感激。

What you want to do is to use a toolbar in the activity. 您要做的是在活动中使用工具栏。 I think that will depend on which theme you use. 我认为这取决于您使用的主题。

@android:style/Theme.DeviceDefault.Light

Will give you a toolbar. 会给你一个工具栏。

Then you set up the button in onCreate in your activity: 然后,在活动中的onCreate中设置按钮:

getActionBar().setDisplayHomeAsUpEnabled(true);

And last you set an action when you click on that back-button: 最后,当您单击该后退按钮时,将设置一个动作:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
    case android.R.id.home:
      onBackPressed();
      return true;
  }

  return super.onOptionsItemSelected(item);
}

It is the onBackPressed() that return you back to the previous activity. onBackPressed()使您返回上一个活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM