如果存在,如何从BackStack恢复Fragment

时间:2013-08-19 03:20:57

标签: android android-fragments back-stack

我正在学习如何使用片段。我有三个Fragment的实例,它们在类的顶部初始化。我将片段添加到这样的活动中:

声明并初始化:

Fragment A = new AFragment();
Fragment B = new BFragment();
Fragment C = new CFragment();

更换/添加:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, A);
ft.addToBackStack(null);
ft.commit();

这些代码段工作正常。每个片段都附加到活动,并且没有任何问题保存到后台。

因此,当我启动ACB时,堆栈如下所示:

| |
|B|
|C|
|A|
___

当我按下“后退”按钮时,B将被销毁并恢复C

但是,当我第二次启动片段A时,不是从后面的堆栈中恢复,而是添加到后面堆栈的顶部

| |
|A|
|C|
|A|
___

但我想恢复A并销毁它上面的所有碎片(如果有的话)。实际上,我只是喜欢默认的后台堆栈行为。

我如何做到这一点?

预期:(A应该恢复,顶部碎片应该被销毁)

| |
| |
| |
|A|
___

编辑:(由A - C建议)

这是我尝试的代码:

private void selectItem(int position) {
        Fragment problemSearch = null, problemStatistics = null;
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();
        String backStateName = null;
        Fragment fragmentName = null;
        boolean fragmentPopped = false;
        switch (position) {
        case 0:
            fragmentName = profile;
            break;
        case 1:
            fragmentName = submissionStatistics;
            break;
        case 2:
            fragmentName = solvedProblemLevel;
            break;
        case 3:
            fragmentName = latestSubmissions;
            break;
        case 4:
            fragmentName = CPExercise;
            break;
        case 5:
            Bundle bundle = new Bundle();
            bundle.putInt("problem_no", problemNo);
            problemSearch = new ProblemWebView();
            problemSearch.setArguments(bundle);
            fragmentName = problemSearch;
            break;
        case 6:
            fragmentName = rankList;
            break;
        case 7:
            fragmentName = liveSubmissions;
            break;
        case 8:
            Bundle bundles = new Bundle();
            bundles.putInt("problem_no", problemNo);
            problemStatistics = new ProblemStatistics();
            problemStatistics.setArguments(bundles);
            fragmentName = problemStatistics;
        default:
            break;
        }
        backStateName = fragmentName.getClass().getName();
        fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
        if (!fragmentPopped) {
            ft.replace(R.id.content_frame, fragmentName);
        }
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.addToBackStack(backStateName);
        ft.commit();

        // I am using drawer layout
        mDrawerList.setItemChecked(position, true);
        setTitle(title[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

问题是,当我启动A然后B时,请按“返回”,B将被删除,A将恢复。然后第二次按'后退'应退出应用程序。但它显示一个空白窗口,我必须再次按回来关闭它。

此外,当我启动A,然后B,然后是C,然后再次B ...

预期:

| |
| |
|B|
|A|
___

实际值:

| |
|B|
|B|
|A|
___

我应该使用任何自定义覆盖onBackPressed()还是我遗漏了什么?

6 个答案:

答案 0 :(得分:258)

读取documentation,有一种方法可以根据事务名称或commit提供的id弹出后台堆栈。使用名称​​可能更容易,因为它不需要跟踪可能改变的数字并强化“唯一的后栈条目”逻辑。

由于每个Fragment只需要一个后向堆栈条目,因此将后面的状态名称设为Fragment的类名(通过getClass().getName())。然后,在替换Fragment时,请使用popBackStackImmediate()方法。如果返回true,则表示后端堆栈中存在Fragment的实例。如果没有,实际执行Fragment替换逻辑。

private void replaceFragment (Fragment fragment){
  String backStateName = fragment.getClass().getName();

  FragmentManager manager = getSupportFragmentManager();
  boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);

  if (!fragmentPopped){ //fragment not in back stack, create it.
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content_frame, fragment);
    ft.addToBackStack(backStateName);
    ft.commit();
  }
}

修改

  

问题是 - 当我启动A然后启动B时,然后按回按钮,B   被删除,A被恢复。并按下后退按钮应该   退出应用程序。但它显示一个空白窗口,需要另一个新闻   关闭它。

这是因为FragmentTransaction被添加到后台堆栈以确保我们可以稍后在顶部弹出片段。如果后端堆栈仅包含1个onBackPressed()

,则快速修复此问题将覆盖Fragment并完成活动
@Override
public void onBackPressed(){
  if (getSupportFragmentManager().getBackStackEntryCount() == 1){
    finish();
  }
  else {
    super.onBackPressed();
  }
}

关于重复的后备栈条目,如果片段尚未弹出,则替换片段的条件语句显然与我原始代码片段的不同。你正在做的是添加到后台堆栈,无论后台堆栈是否被弹出。

这样的事情应该更接近你想要的东西:

private void replaceFragment (Fragment fragment){
  String backStateName =  fragment.getClass().getName();
  String fragmentTag = backStateName;

  FragmentManager manager = getSupportFragmentManager();
  boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);

  if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null){ //fragment not in back stack, create it.
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content_frame, fragment, fragmentTag);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.addToBackStack(backStateName);
    ft.commit();
  } 
}

条件有点改变,因为选择相同的片段,而它可见也导致重复的条目。

实现:

我强烈建议您不要像在代码中那样使用更新的replaceFragment()方法。所有逻辑都包含在此方法中,并且移动部件可能会导致问题。

这意味着您应该将更新的replaceFragment()方法复制到您的课程中,然后更改

backStateName = fragmentName.getClass().getName();
fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped) {
            ft.replace(R.id.content_frame, fragmentName);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(backStateName);
ft.commit();

所以它只是

replaceFragment (fragmentName);

编辑#2

要在后台堆栈更改时更新抽屉,请创建一个在片段中接受的方法并比较类名称。如果匹配,请更改标题和选择。如果有有效的片段,还要添加OnBackStackChangedListener并让它调用您的更新方法。

例如,在活动的onCreate()中,添加

getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() {

  @Override
  public void onBackStackChanged() {
    Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_frame);
    if (f != null){
      updateTitleAndDrawer (f);
    }

  }
});

另一种方法:

private void updateTitleAndDrawer (Fragment fragment){
  String fragClassName = fragment.getClass().getName();

  if (fragClassName.equals(A.class.getName())){
    setTitle ("A");
    //set selected item position, etc
  }
  else if (fragClassName.equals(B.class.getName())){
    setTitle ("B");
    //set selected item position, etc
  }
  else if (fragClassName.equals(C.class.getName())){
    setTitle ("C");
    //set selected item position, etc
  }
}

现在,每当后台堆栈发生变化时,标题和已检查位置将反映可见Fragment

答案 1 :(得分:7)

我认为这种方法可以解决您的问题:

public static void attachFragment ( int fragmentHolderLayoutId, Fragment fragment, Context context, String tag ) {


    FragmentManager manager = ( (AppCompatActivity) context ).getSupportFragmentManager ();
    FragmentTransaction ft = manager.beginTransaction ();

    if (manager.findFragmentByTag ( tag ) == null) { // No fragment in backStack with same tag..
        ft.add ( fragmentHolderLayoutId, fragment, tag );
        ft.addToBackStack ( tag );
        ft.commit ();
    }
    else {
        ft.show ( manager.findFragmentByTag ( tag ) ).commit ();
    }
}

最初发布于 This Question

答案 2 :(得分:3)

第1步:使用您的活动类实现接口

public class AuthenticatedMainActivity extends Activity implements FragmentManager.OnBackStackChangedListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        .............
        FragmentManager fragmentManager = getFragmentManager();           
        fragmentManager.beginTransaction().add(R.id.frame_container,fragment, "First").addToBackStack(null).commit();
    }

    private void switchFragment(Fragment fragment){            
      FragmentManager fragmentManager = getFragmentManager();
      fragmentManager.beginTransaction()
        .replace(R.id.frame_container, fragment).addToBackStack("Tag").commit();
    }

    @Override
    public void onBackStackChanged() {
    FragmentManager fragmentManager = getFragmentManager();

    System.out.println("@Class: SummaryUser : onBackStackChanged " 
            + fragmentManager.getBackStackEntryCount());

    int count = fragmentManager.getBackStackEntryCount();

    // when a fragment come from another the status will be zero
    if(count == 0){

        System.out.println("again loading user data");

        // reload the page if user saved the profile data

        if(!objPublicDelegate.checkNetworkStatus()){

            objPublicDelegate.showAlertDialog("Warning"
                    , "Please check your internet connection");

        }else {

            objLoadingDialog.show("Refreshing data..."); 

            mNetworkMaster.runUserSummaryAsync();
        }

        // IMPORTANT: remove the current fragment from stack to avoid new instance
        fragmentManager.removeOnBackStackChangedListener(this);

    }// end if
   }       
}

第2步:当您调用另一个片段时,请添加以下方法:

String backStateName = this.getClass().getName();

FragmentManager fragmentManager = getFragmentManager();
fragmentManager.addOnBackStackChangedListener(this); 

Fragment fragmentGraph = new GraphFragment();
Bundle bundle = new Bundle();
bundle.putString("graphTag",  view.getTag().toString());
fragmentGraph.setArguments(bundle);

fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragmentGraph)
.addToBackStack(backStateName)
.commit();

答案 3 :(得分:0)

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {

    @Override
    public void onBackStackChanged() {

        if(getFragmentManager().getBackStackEntryCount()==0) {
            onResume();
        }    
    }
});

答案 4 :(得分:0)

更容易的解决方案是更改此行

ft.replace(R.id.content_frame, A);ft.add(R.id.content_frame, A);

在您的XML布局内,请使用

  android:background="@color/white"
  android:clickable="true"
  android:focusable="true"

Clickable表示可以通过指针设备单击它或通过触摸设备点击它。

Focusable意味着它可以从键盘等输入设备获得焦点。诸如键盘之类的输入设备无法根据输入本身来决定将其输入事件发送到哪个视图,因此它们会将它们发送到具有焦点的视图。

答案 5 :(得分:0)

  

我知道现在回答这个问题已经很晚了,但是我自己解决了这个问题,并认为值得与大家分享。”

public void replaceFragment(BaseFragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    final FragmentManager fManager = getSupportFragmentManager();
    BaseFragment fragm = (BaseFragment) fManager.findFragmentByTag(fragment.getFragmentTag());
    transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);

    if (fragm == null) {  //here fragment is not available in the stack
        transaction.replace(R.id.container, fragment, fragment.getFragmentTag());
        transaction.addToBackStack(fragment.getFragmentTag());
    } else { 
        //fragment was found in the stack , now we can reuse the fragment
        // please do not add in back stack else it will add transaction in back stack
        transaction.replace(R.id.container, fragm, fragm.getFragmentTag()); 
    }
    transaction.commit();
}
  

并在onBackPressed()

 @Override
public void onBackPressed() {
    if(getSupportFragmentManager().getBackStackEntryCount()>1){
        super.onBackPressed();
    }else{
        finish();
    }
}