Android Fragments Android -保存/恢复片段状态

cx6n0qe3  于 2023-10-19  发布在  Android
关注(0)|答案(8)|浏览(183)

我有一个活动,其中我经历了几个片段。在每个片段中,我有几个视图(EditText, ListView, Map等)。
我如何保存在那一刻显示的片段的示例?我需要它的工作时,活动是onPause() --> onResume()。我也需要它的工作,当我从另一个片段(从backstack弹出)返回。
从主Activity调用第一个片段,然后从片段调用下一个片段。
我的活动代码:

public class Activity_Main extends FragmentActivity{

public static Fragment_1 fragment_1;
public static Fragment_2 fragment_2;
public static Fragment_3 fragment_3;
public static FragmentManager fragmentManager;

@Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

     fragment_1 = new Fragment_1();

     fragment_2 = new Fragment_2();

     fragment_3 = new Fragment_3();

     fragmentManager = getSupportFragmentManager();
     FragmentTransaction transaction_1 = fragmentManager.beginTransaction();
     transaction_1.replace(R.id.content_frame, fragment_1);
     transaction_1.commit();
}}

下面是我的一个片段的代码:

public class Fragment_1 extends Fragment {

      private EditText title;
      private Button go_next;

      @Override
      public View onCreateView(final LayoutInflater inflater,
        ViewGroup container, Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.fragment_1,
            container, false);

            title = (EditText) rootView.findViewById(R.id.title);

            go_next = (Button) rootView.findViewById(R.id.go_next);

            image.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View v) {

                 FragmentTransaction transaction_2 = Activity_Main.fragmentManager
                .beginTransaction();

                 transaction_2.replace(R.id.content_frame,
                  Activity_Main.fragment_2);
                 transaction_2.addToBackStack(null);
                 transaction_2.commit();  

            });
        }}

我查了很多资料,但都不清楚。谁能给予一个明确的解决方案和一个例子,好吗?

0s0u357o

0s0u357o1#

当一个片段被移到backstack时,它不会被销毁。所有示例变量都保留在那里。这就是保存数据的地方。在onActivityCreated中,检查以下条件:
1.是包裹!= null?如果是,则数据保存在该位置(可能是方向更改)。
1.是否有数据保存在示例变量中?如果是的话,从它们中恢复你的状态(或者什么都不做,因为一切都是应该的)。
1.否则你的片段是第一次显示,重新创建一切。
编辑:这里有一个例子

public class ExampleFragment extends Fragment {
    private List<String> myData;

    @Override
    public void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("list", (Serializable) myData);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (savedInstanceState != null) {
            //probably orientation change
            myData = (List<String>) savedInstanceState.getSerializable("list");
        } else {
            if (myData != null) {
                //returning from backstack, data is fine, do nothing
            } else {
                //newly created, compute data
                myData = computeData();
            }
        }
    }
}
f45qwnt8

f45qwnt82#

Android的Fragment有一些优点和一些缺点。Fragment最大的缺点是,当你想使用一个片段时,你只需要创建一次。当您使用它时,每次都会调用片段的onCreateView。如果你想在片段中保留组件的状态,你必须保存片段状态,并且你必须在下一个显示中加载它的状态。
这使得片段视图有点慢和奇怪。
我找到了一个解决方案,并使用了这个解决方案:“一切都很好。每个人都可以尝试”。
当第一次运行onCreateView时,创建视图作为全局变量。当你第二次调用这个片段onCreateView时,你可以返回这个全局视图。片段组件状态将被保留。

View view;

@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    setActionBar(null);
    if (view != null) {
        if ((ViewGroup)view.getParent() != null)
            ((ViewGroup)view.getParent()).removeView(view);
        return view; 
    }
    view = inflater.inflate(R.layout.mylayout, container, false);
}
vybvopom

vybvopom3#

试试这个:

@Override
protected void onPause() {
    super.onPause();
    if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null)
        getSupportFragmentManager().findFragmentByTag("MyFragment").setRetainInstance(true);
}

@Override
protected void onResume() {
    super.onResume();
    if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null)
        getSupportFragmentManager().findFragmentByTag("MyFragment").getRetainInstance();
}

希望这会有帮助。
你也可以把这个写在menifest文件中的activity标签中:

android:configChanges="orientation|screenSize"

祝你好运!!

2izufjch

2izufjch4#

为了保存Fragment状态,需要实现onSaveInstanceState():“与Activity一样,您可以使用Bundle保留片段的状态,以防Activity的进程被终止,并且您需要在Activity重新创建时恢复片段状态。您可以在片段的onSaveInstanceState()回调期间保存状态,并在onCreate()onCreateView()onActivityCreated()期间恢复它。有关保存状态的详细信息,请参阅活动文档。”
http://developer.android.com/guide/components/fragments.html#Lifecycle

hzbexzde

hzbexzde5#

如这里所述:Why use Fragment#setRetainInstance(boolean)?
你也可以像这样使用fragments方法setRetainInstance(true)

public class MyFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // keep the fragment and all its data across screen rotation
        setRetainInstance(true);

    }
}
ecr0jaav

ecr0jaav6#

你可以从fragmentManager获取当前的Fragment。如果片段管理器中没有它们,则可以创建Fragment_1

public class MainActivity extends FragmentActivity {

    public static Fragment_1 fragment_1;
    public static Fragment_2 fragment_2;
    public static Fragment_3 fragment_3;
    public static FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.main);

        fragment_1 = (Fragment_1) fragmentManager.findFragmentByTag("fragment1");

        fragment_2  =(Fragment_2) fragmentManager.findFragmentByTag("fragment2");

        fragment_3 = (Fragment_3) fragmentManager.findFragmentByTag("fragment3");

        if(fragment_1==null && fragment_2==null && fragment_3==null){           
            fragment_1 = new Fragment_1();          
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment_1, "fragment1").commit();
        }

    }

}

你也可以使用setRetainInstance来实现它的功能它忽略片段中的onDestroy()方法,你的应用程序将回到后台,os杀死你的应用程序来分配更多的内存,你将需要保存所有你需要的数据在onSaveInstanceState包中

public class Fragment_1 extends Fragment {

    private EditText title;
    private Button go_next;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true); //Will ignore onDestroy Method (Nested Fragments no need this if parent have it)
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        onRestoreInstanceStae(savedInstanceState);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    //Here you can restore saved data in onSaveInstanceState Bundle
    private void onRestoreInstanceState(Bundle savedInstanceState){
        if(savedInstanceState!=null){
            String SomeText = savedInstanceState.getString("title");            
        }
    }

    //Here you Save your data
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("title", "Some Text");
    }

}
5gfr0r5j

5gfr0r5j7#

我不确定这个问题是否仍然困扰着你,因为它已经几个月了。但我想分享一下我是如何处理的。下面是源代码:

int FLAG = 0;
private View rootView;
private LinearLayout parentView;

/**
 * The fragment argument representing the section number for this fragment.
 */
private static final String ARG_SECTION_NUMBER = "section_number";

/**
 * Returns a new instance of this fragment for the given section number.
 */
public static Fragment2 newInstance(Bundle bundle) {
    Fragment2 fragment = new Fragment2();
    Bundle args = bundle;
    fragment.setArguments(args);
    return fragment;
}

public Fragment2() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    Log.e("onCreateView","onCreateView");
    if(FLAG!=12321){
        rootView = inflater.inflate(R.layout.fragment_create_new_album, container, false);
        changeFLAG(12321);
    }       
    parentView=new LinearLayout(getActivity());
    parentView.addView(rootView);

    return parentView;
}

/* (non-Javadoc)
 * @see android.support.v4.app.Fragment#onDestroy()
 */
@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    Log.e("onDestroy","onDestroy");
}

/* (non-Javadoc)
 * @see android.support.v4.app.Fragment#onStart()
 */
@Override
public void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    Log.e("onstart","onstart");
}

/* (non-Javadoc)
 * @see android.support.v4.app.Fragment#onStop()
 */
@Override
public void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
    if(false){
        Bundle savedInstance=getArguments();
        LinearLayout viewParent;

        viewParent= (LinearLayout) rootView.getParent();
        viewParent.removeView(rootView);

    }
    parentView.removeView(rootView);

    Log.e("onStop","onstop");
}
@Override
public void onPause() {
    super.onPause();
    Log.e("onpause","onpause");
}

@Override
public void onResume() {
    super.onResume();
    Log.e("onResume","onResume");
}

这里是MainActivity:

/**
 * Fragment managing the behaviors, interactions and presentation of the
 * navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in
 * {@link #restoreActionBar()}.
 */

public static boolean fragment2InstanceExists=false;
public static Fragment2 fragment2=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.activity_main);

    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
            .findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
    switch(position){
    case 0:
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.container, Fragment1.newInstance(position+1)).commit();
        break;
    case 1:

        Bundle bundle=new Bundle();
        bundle.putInt("source_of_create",CommonMethods.CREATE_FROM_ACTIVITY);

        if(!fragment2InstanceExists){
            fragment2=Fragment2.newInstance(bundle);
            fragment2InstanceExists=true;
        }
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.container, fragment2).commit();

        break;
    case 2:
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.container, FolderExplorerFragment.newInstance(position+1)).commit();
        break;
    default: 
        break;
    }
}

parentView是关键点。通常情况下,当onCreateView时,我们只需返回rootView。但是现在,我将rootView添加到parentView,然后返回parentView。为了防止“指定的子级已经有父级。你必须在...”错误时调用removeView(),我们需要调用parentView.removeView(rootView),否则我提供的方法就没用了。我也想分享一下我是如何找到它的。首先,我设置了一个布尔值来指示示例是否存在。当示例存在时,rootView不会再次膨胀。但是后来,logcat给了孩子一个已经有父的东西,所以我决定使用另一个父视图作为中间父视图。就是这样
希望对你有帮助。

w8f9ii69

w8f9ii698#

如果你使用bottombar和insted的viewpager你想设置自定义片段替换逻辑与检索以前的保存状态你可以做使用下面的代码

String current_frag_tag = null;
 String prev_frag_tag = null;


    @Override
    public void onTabSelected(TabLayout.Tab tab) {
   

        switch (tab.getPosition()) {
            case 0:

                replaceFragment(new Fragment1(), "Fragment1");
                break;

            case 1:
                replaceFragment(new Fragment2(), "Fragment2");
                break;

            case 2:
                replaceFragment(new Fragment3(), "Fragment3");
                break;

            case 3:
               replaceFragment(new Fragment4(), "Fragment4");
                break;

            default:
                replaceFragment(new Fragment1(), "Fragment1");
                break;

        }

    public void replaceFragment(Fragment fragment, String tag) {
        if (current_frag_tag != null) {
            prev_frag_tag = current_frag_tag;
        }

        current_frag_tag = tag;

        FragmentManager manager = null;
        try {
            manager = requireActivity().getSupportFragmentManager();
            FragmentTransaction ft = manager.beginTransaction();

            if (manager.findFragmentByTag(current_frag_tag) == null) { // No fragment in backStack with same tag..
                ft.add(R.id.viewpagerLayout, fragment, current_frag_tag);

                if (prev_frag_tag != null) {
                    try {
                        ft.hide(Objects.requireNonNull(manager.findFragmentByTag(prev_frag_tag)));
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                }
//            ft.show(manager.findFragmentByTag(current_frag_tag));
                ft.addToBackStack(current_frag_tag);
                ft.commit();

            } else {

                try {
                    ft.hide(Objects.requireNonNull(manager.findFragmentByTag(prev_frag_tag)))
                            .show(Objects.requireNonNull(manager.findFragmentByTag(current_frag_tag))).commit();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }



    }

在子片段中,您可以使用以下方法注解访问片段是否可见:你必须在子片段中实现下面的方法

@Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        try {
            if(hidden){
                adapter.getFragment(mainVideoBinding.viewPagerVideoMain.getCurrentItem()).onPause();
            }else{
                adapter.getFragment(mainVideoBinding.viewPagerVideoMain.getCurrentItem()).onResume();
            }
        }catch (Exception e){
       }

    }

相关问题