在两个片段之间切换

在两个片段之间切换

本文介绍了在两个片段之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做以下事情.首先有两个片段.必要时在它们之间进行过渡.当我从第二个片段中的第一个片段开始时,首先将其存储在堆栈中.当我单击后退"按钮时,第二个片段将被删除,并从堆栈中返回第一个片段.再次,我不能进入第二个片段-它已被删除.我该如何解决这个问题?

I want to do the following. There are two fragments first and second. Necessary make the transition between them. When I go from first fragment in the second, first stored in the stack. When I click the Back button the second fragment is removed and returned first fragment from the stack. Again I can not go in the second fragment - it has been deleted. How can I solve this problem?

在主要活动中(对Fragment1的回调):

In main activity (callback for Fragment1):

@Override
public void onNavigate() {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    Fragment1 newFragment1 = (Fragment1) getFragmentManager().findFragmentByTag("frag_1");
    Fragment2 newFragment2 = (Fragment2) getFragmentManager().findFragmentByTag("frag_2");
    ft.replace(R.id.main, newFragment2);
    ft.remove(newFragment1);
    ft.addToBackStack(null);
    ft.commit();
}

我动态添加的片段:

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.add(R.id.main, new Fragment1(), "frag_1");
    ft.add(R.id.main, new Fragment2(), "frag_2");
    ft.commit();

推荐答案

我解决了这个问题:).我隐藏了第一个片段,并将事务添加到后堆栈中.当我单击返回"按钮时,我将返回片段

I solved this problem :). I hide first fragment and add transaction to the back stack. When I click button Back I return to fragment

@Override
public void onNavigate() {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    Fragment1 newFragment1 = (Fragment1) getFragmentManager().findFragmentByTag("frag_1");
    ft.hide(newFragment1);
    ft.addToBackStack(null);
    ft.commit();
}

这篇关于在两个片段之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 08:30