简体   繁体   English

Android将片段保存到导航抽屉中

[英]Android save Fragments into Navigation Drawer

in my program i have some Fragments and i can replace each Fragment by click on that with this code. 在我的程序中,我有一些片段,通过单击此代码,可以替换每个片段。 my problem is this: those fragments are low to load and after click on each Fragments create new from it and cause of load again after clicked on fragment. 我的问题是:这些片段加载不足,单击每个片段后会从中创建新片段,并在单击片段后再次导致加载。 how to save fragment content or state and prevent to reload? 如何保存片段内容或状态并防止重新加载?

@Override
    public void onNavigationDrawerItemSelected(int position) {
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = new InfoFragment();
                break;
            case 1:
                fragment = new ParentOtoFragment();
                break;
            case 2:
                fragment = new ParentProFragment();
                break;
            case 3:
                fragment = new SupportFragment();
                break;
            case 4:
                fragment = new AboutFragment();
                break;
        }
        if (fragment != null){
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container,fragment).commit();
        }
    }

POST UPDATE 发布更新

after reply to this topic by @Vikram Ezhil i'm initials fragments and fragmentTAG into constructor and change @Vikram Ezhil code to this below code, my problem is solved. 通过@Vikram伊士希尔回复这个主题后,我很缩写fragmentsfragmentTAG到构造和变化@Vikram伊士希尔代码,这下面的代码,我的问题就解决了。

@Override
   public void onNavigationDrawerItemSelected(int position) {
       FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
       fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

       if (getSupportFragmentManager().findFragmentByTag(fragmentTAGS[position]) == null) {
           fragmentTransaction.add(R.id.container, fragments[position], fragmentTAGS[position]);
       }
       for (int i = 0; i < fragments.length; i++) {
           if (i == position) {
               fragmentTransaction.show(fragments[i]);
           } else {
               if (getSupportFragmentManager().findFragmentByTag(fragmentTAGS[position]) != null) {
                   fragmentTransaction.hide(fragments[i]);
               }
           }
       }
       fragmentTransaction.commit();
   }

To prevent the fragments from re-creating from scratch every time you click on an item from the navigation drawer you need to use 为防止每次从导航抽屉中单击某个项目时从头开始重新创建片段,您需要使用

fragmentTransaction.add(R.id.container,fragment).commit();

instead of 代替

fragmentTransaction.replace(R.id.container,fragment).commit();

However some extra bit of work is required when you add fragments instead of replacing them. 但是,当您添加片段而不是替换它们时,需要一些额外的工作。

  1. You need to make sure the the same fragment is not added more than once. 您需要确保同一片段不会被添加多次。 You can place a fragment TAG and check if the TAG exists before adding a fragment. 您可以放置​​片段TAG,并在添加片段之前检查TAG是否存在。 Example, 例,

     if (getFragmentManager().findFragmentByTag("fragment1_tag") == null) { fragmentTransaction.add(R.id.container, fragment1, "fragment1_tag"); } 
  2. You need to hide the fragments which are not shown, since when you start adding fragments they will be overlapping with each other on screen. 您需要隐藏未显示的片段,因为当您开始添加片段时,它们将在屏幕上相互重叠。

     if (getFragmentManager().findFragmentByTag("fragment1_tag") != null) { fragmentTransaction.hide(fragment1); } 
  3. Use interface methods whenever you want to update a specific part in a fragment. 每当您要更新片段中的特定部分时,请使用接口方法。 I will not go in depth into this, since this is altogether a different topic. 我不会对此进行深入探讨,因为这完全是一个不同的主题。

  4. Make sure your fragments are not over-lapped once the application is killed by the android OS to allocate memory for other apps ( check out this post for more info ). 一旦应用程序被Android OS杀死以为其他应用程序分配内存,请确保您的片段没有重叠,( 请查看此帖子以获取更多信息 )。

Also adding some suggestions - from your above code, you are having only one fragment variable and re-using it for all the 5 screens. 还添加了一些建议-从以上代码中,您只有一个fragment变量,并将其重新用于所有5个屏幕。 I would recommend you to have separate fragment variable for the 5 screens and save it an array. 我建议您为5个屏幕使用单独的片段变量,并将其保存为数组。

The reason being this would be far more easier and generic to control when you start adding, hiding, showing fragments. 原因是当您开始添加,隐藏和显示片段时,这将更加容易控制。 Example, 例,

InfoFragment fragment1 = new InfoFragment();
ParentOtoFragment fragment2 = new ParentOtoFragment();
ParentProFragment fragment3 = new ParentProFragment();
SupportFragment fragment4 = new SupportFragment();
AboutFragment fragment5 = new AboutFragment();

Fragment[] fragments = new Fragment[]{fragment1,fragment2,fragment3,fragment4,fragment5};
String[] fragmentTAGS = new String[]{"fragment1_tag","fragment2_tag","fragment3_tag","fragment4_tag","fragment5_tag"};

Now using the above, you can switch between fragments based on the item clicked from your navigation drawer. 现在,使用以上内容,您可以根据从导航抽屉中单击的项目在片段之间切换。

@Override
public void onNavigationDrawerItemSelected(int position) 
{
      // Add the fragments only once if array haven't fragment
      if (getFragmentManager().findFragmentByTag(fragmentTAGS[position]) == null)
      {
          fragmentTransaction.add(R.id.container,fragments[position],fragmentTAGS[position]);
      };

      // Hiding & Showing fragments
      for(int catx=0;catx<fragments.length;catx++)
      {
         if(catx == position)
         {
              fragmentTransaction.show(fragments[catx]);
         }
         else
         {
              // Check if the fragment is added and then hide it
              if (getFragmentManager().findFragmentByTag(fragmentTAGS[catx]) != null)
              {
                  fragmentTransaction.hide(fragments[catx]);
              };
         };
      };

      fragmentTransaction.commit();
};

Based on the previous answer i developed the following solution, hope it helps someone: 根据先前的答案,我开发了以下解决方案,希望它对某人有所帮助:

1.Declare an array with all your fragments: 1,声明一个包含所有片段的数组:

private Fragment[] fragments = new Fragment[] { new frag1(), new frag2()};

2.When onNavigationItemSelected fires an event: 2.当onNavigationItemSelected触发事件时:

        Fragment fragment = null;
        switch (itemId) {
            case R.id.nav_frag1:
                fragment = fragments[0];
                break;
            case R.id.nav_frag2:
                fragment = fragments[1];
                break;
            default:
                return;
        }

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_main, fragment);
        ft.commit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM