如何摆脱Android应用栏中的后退按钮

Posted

技术标签:

【中文标题】如何摆脱Android应用栏中的后退按钮【英文标题】:How to get rid of back button in Android app bar 【发布时间】:2021-08-06 11:02:39 【问题描述】:

我有一个简单的活动,其中包含用户可以在多个片段之间切换。只有在显示第一个 Fragment 时,应用栏中才会出现一个后退按钮。

我已经尝试通过将其添加到我的活动中来删除代码中的后退按钮:

@Override
public boolean onCreateOptionsMenu(Menu menu) 

    if (getSupportActionBar() != null) 
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setHomeButtonEnabled(false);
    

    return super.onCreateOptionsMenu(menu);

但这不能正常工作:最初后退按钮实际上消失了(耶!)。但是一旦我切换到另一个片段然后回到第一个片段,后退按钮又会出现。

这个后退按钮是从哪里来的? 如何永久禁用它?

【问题讨论】:

【参考方案1】:

查看 xml 文件,您会在其中添加工具栏吗 并尝试

setSupportActionBar()=null;

【讨论】:

【参考方案2】:
You are advised to use the android toolbar to replace the Actionbar.
1. Go to the Android Manifest file and find the theme to be used.
Generally, the default value is android:theme="@style/AppTheme". You only need to change the first line to Theme.AppCompat.Light.NoActionBar.
2. Write the toolbar control to the layout file.

    <android.support.v7.widget.Toolbar
android:layout_
android:id="@+id/toolbar"
android:background="@color/colorPrimary"
app:title="bar"
android:layout_>
</android.support.v7.widget.Toolbar>

3. In the java file
Bind the toolbar and invoke the setSupportActionBar() method to set the current menu bar to the bound toolbar object.
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
If you want to use the return button, add the returned listener finish:

    toolbar.setNavigationOnClickListener(new View.OnClickListener() 
@Override
public void onClick(View v) 
onBackPressed();

);

【讨论】:

以上是关于如何摆脱Android应用栏中的后退按钮的主要内容,如果未能解决你的问题,请参考以下文章

Android - 标题栏中的后退按钮

如何在底部应用栏中使用后退按钮实现导航。安卓

无法删除 sliver 应用栏中的后退按钮

如何覆盖android中的操作栏后退按钮?

如何更改 iOS 13 导航栏中的后退按钮图像?

如何在 uiviewcontroller 的导航栏中添加后退按钮?