简体   繁体   English

在片段Android中保存数据

[英]Saving data in fragment android

I have been trying to achieve a certain functionality related to contacts.I have a fragment that shows all the contacts in the device.At first when fragment instance created the contacts will be fetched and stored on a arraylist which will then be displayed in a listview. 我一直在尝试实现与联系人有关的某些功能。我有一个片段来显示设备中的所有联系人。首先,当片段实例创建时,联系人将被提取并存储在arraylist中,然后将其显示在列表视图中。 When fetching for first time,it takes about roughly 3-5 seconds to load contacts,so I have a loading view placed.Is there any way to save this list and retain it back so the fetching of contact list is faster second time.I am replacing fragments on button presses..here is my code. 第一次获取时,加载联系人大约需要3-5秒,所以我放置了一个加载视图。是否有任何方法可以保存此列表并将其保留回去,因此第二次获取联系人列表的速度更快。正在替换按钮按下时的片段。这是我的代码。

public static void replaceFragment(FragmentManager fm, int container, Fragment fragment) {
    FragmentTransaction ft = fm.beginTransaction();
    ft.replace(container, fragment);
    ft.commit();
}

and called in activity's onCreate() . 并调用了活动的onCreate()

 Utils.replaceFragment(getSupportFragmentManager(), R.id.container, new Fragment1());

also on every button press in activity I am calling this method.. 在活动中每按一次按钮,我都会调用此方法。

@Override
public void onClick(View v) {
    Typeface tf;
    switch (v.getId()) {
        case R.id.frag1_btn:
            Utils.replaceFragment(getSupportFragmentManager(), R.id.container, new Fragment1());
            break;

        case R.id.contact_btn:
            Utils.replaceFragment(getSupportFragmentManager(),
                        R.id.container, new ContactFragment());
            break;
    }
}

I have searched about saveToBackStack() method and onsavedInstanceState(Bundle) and onRetainSavedInstance() , but can they be used here in my case? 我已经搜索过saveToBackStack()方法以及onsavedInstanceState(Bundle)onRetainSavedInstance() ,但是我可以在这里使用它们吗? Also to use these is addToBackStack() method needed?..I' m still a novice at this.Any suggestions? 还要使用这些还需要addToBackStack()方法吗?我还是这个新手。有什么建议吗?

When you replace the Fragment, you are creating a new instance of your Fragment, then fragment previous state never will be restored. 当您替换Fragment时,您正在创建Fragment的新实例,那么片段以前的状态将永远不会恢复。

Utils.replaceFragment(getSupportFragmentManager(), R.id.container, new Fragment1());

Maybe you could use 2 containers, one for each fragment, and instead of replace the framents, show and hide them. 也许您可以使用2个容器,每个片段一个,而不是替换框架,而是显示和隐藏它们。 If you do that you will can get the previous instance of your fragment. 如果这样做,您将获得片段的先前实例。

http://developer.android.com/reference/android/app/FragmentManager.html#findFragmentById(int) http://developer.android.com/reference/android/app/FragmentManager.html#findFragmentById(int)

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

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