在按下后退按钮的片段中,活动为空白 [英] In Fragment on back button pressed Activity is blank

查看:32
本文介绍了在按下后退按钮的片段中,活动为空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动和许多片段在同一个 FrameLayout

I have an Activity and many fragments inflated in same FrameLayout

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

示例:mainActivity > 任何片段(按返回按​​钮)> 活动为空.

example: mainActivity > any fragment (press back button) > activity is blank.

在onCreate中:

In onCreate:

layout = (FrameLayout)findViewById(R.id.content_frame);
layout.setVisibility(View.GONE);

当我开始一个片段时:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, profileFragment);
ft.addToBackStack(null);
ft.commit();
layout.setVisibility(View.VISIBLE);

我想我需要在按下后再次使 frameLayout 的可见性 GONE,但我该怎么做?

I suppose I need to make the frameLayout's visibility GONE again on back pressed, but how do I do this?

我尝试了 onBackPressed 并设置了 layout.setVisibility(View.GONE); 但我无法返回片段,因为我直接进入主页.

I tried onBackPressed and set layout.setVisibility(View.GONE); but I cannot go back through fragments, as I go directly to main page.

推荐答案

如果您在活动中使用了多个片段,或者即使您只有一个片段,那么第一个片段不应定义 addToBackStack.由于这允许返回导航并且在此片段之前将显示空的活动布局.

If you have more than one fragment been used in the activity or even if you have only one fragment then the first fragment should not have addToBackStack defined. Since this allows back navigation and prior to this fragment the empty activity layout will be displayed.

 // fragmentTransaction.addToBackStack() // dont include this for your first fragment.

但是对于另一个片段,您需要定义它,否则背面将不会导航到较早的屏幕(片段),而应用程序可能会关闭.

But for the other fragment you need to have this defined otherwise the back will not navigate to earlier screen (fragment) instead the application might shutdown.

这篇关于在按下后退按钮的片段中,活动为空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆