本文介绍了用片段实现后栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在使用片段时实现后退堆栈,但是当使用后退"按钮时,我一直被带出应用程序并回到主屏幕.

I'm attempting to implement a back stack while using fragments, but when using the Back button, I keep getting taken out of the app to the home screen.

活动打开片段A;片段A具有可单击的TextView,可打开片段B(此方法有效).击回BACK应该使我回到片段A,但它将我带到主屏幕.

Activity opens fragment A; Fragment A has a clickable TextView that opens fragment B (this works). Hitting BACK should return me to fragment A, but it takes me to the home screen instead.

这是活动调用onCreate中片段A的开头:

Here is the activity's call to the opening of fragment A in onCreate:

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.fragment_layout_container, new FragmentLogin(), "fragment_login")
            .addToBackStack("login_screen")
            .commit();

    Log.d("Back", getFragmentManager().getBackStackEntryCount() +" <- Entry Count at LoginActivity.onCreate" );

这时,日志将显示0 <- Entry Count at LoginActivity.onCreate.我做错了某事,使它无法打印1.

At this point, the Log prints 0 <- Entry Count at LoginActivity.onCreate. Something I've done wrong keeps this from printing 1.

然后,片段A具有此侦听器:

Then, the Fragment A has this listener:

    forgottenPassword.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_layout_container, new FragmentForgottenPassword(), "fragment_password")
                    .addToBackStack("forgotten_password")
                    .commit();

            Log.d("Back", getFragmentManager().getBackStackEntryCount() + " <- Entry Count at FragmentLogin.onCreateView.Listener");
        }
    });

这里的日志打印1 <- Entry Count at FragmentLogin.onCreateView.Listener.在这里,侦听器工作并打开片段B-但后退按钮使我返回主屏幕.

The Log here prints 1 <- Entry Count at FragmentLogin.onCreateView.Listener. Here, the listener works and opens fragment B - but the back button returns me to the home screen.

推荐答案

在活动"中使用它应该弹出已经添加到后退堆栈中的片段

Use this in your Activity it should pop out the fragments already added to backstack

 @Override
 public void onBackPressed()
 {
     if (getFragmentManager().getBackStackEntryCount() > 0) {
         getFragmentManager().popBackStack();
     } else {
         super.onBackPressed();
     }
 }

这篇关于用片段实现后栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 13:07