Android的 - 后退按钮和碎片backstack不工作碎片、按钮、工作、Android

2023-09-05 04:29:54 作者:阿姨我是你闺女的对象_

我正在开发一个简单的基于片段的应用程序单张FragmentActivity。应用程序的每个屏幕被包含在一个片段和所有片段被添加到在应用程序启动容器布局。

I'm developing a simple fragment-based application with a singe FragmentActivity. Each 'screen' of the application is contained in a fragment and all fragments are added to the container layout at application startup.

// Set up fragments in Main Activity
fragMan = getFragmentManager();
FragmentTransaction ft = fragMan.beginTransaction();
ft.add(R.id.fragment_container, settingsFragment);
ft.add(R.id.fragment_container, mapFragment);
ft.add(R.id.fragment_container, tracksFragment);
ft.add(R.id.fragment_container, waypointsFragment);
ft.commit();

转换是通过隐藏当前可见的片段,然后显示出相应的片段来完成。

Transitions are accomplished by hiding the currently visible fragment, then showing the appropriate fragment.

ft = fragMan.beginTransaction();
ft.show(mapFragment);
ft.addToBackStack(null);
ft.commit();

这一切工作正常,但是当后退按钮是pressed,应用程序退出,无论屏幕是可见的或者是previous交易已被添加到后退堆栈。

This all works fine, but when the back button is pressed, the application exits, regardless of which screen is visible or what previous transactions have been added to the back stack.

我检查,以确保背部叠正确累积记录,并试图过渡方法许多不同的变化,如更换片段,而不是隐藏/显示它们,创建片段的新实例,而不是将它们存储在变量,等。据我所知,我的code匹配所有的教程和例子我能找到的,我还没有能够找到任何类似的问题/类似问题的例子,presumably因为标准实施只是工作为别人着想。

I've checked to make sure that the back stack is properly accumulating records and tried many different variations of transition methods such as replacing fragments rather than hiding/showing them, creating new instances of fragments rather than storing them in variables, etc. As far as I can tell, my code matches all the tutorials and examples I can find, and I haven't even been able to find any similar questions/examples of similar problems, presumably because the standard implementation 'just works' for others.

我怀疑它可能是在应用层面的问题,如在我的清单属性(我已经彻底的调查pretty的)或固有的东西,其中prevents在我的应用程序设置的方式从正常的后退按钮。我可以覆盖onBack pssed手工处理过渡$ P $,但是这似乎是一个非常丑陋的解决方法。任何想法,为什么这可能无法按预期?顺便说一句,这是在一台Nexus 7上运行果冻豆。

I suspect it may be a problem at the application level such as a property in my manifest (which I've investigated pretty thoroughly) or something inherent to the way my application is set up which prevents the back button from functioning properly. I can override onBackPressed to handle the transitions manually, but this seems like a very ugly workaround. Any ideas as to why this might not be behaving as expected? By the way this is on a Nexus 7 running Jelly Bean.

推荐答案

而不是活动检查是否正在使用FragmentActivity(从支持库)。这将导致backstack和转型的问题。

Check if you are using FragmentActivity(from support library) instead of Activity. This will cause backstack and transition problem.