gpt4 book ai didi

android - 一个 Activity,多个 Fragments 和 setRetainInstance

转载 作者:行者123 更新时间:2023-11-29 16:09:46 25 4
gpt4 key购买 nike

在我的应用程序中,我使用了一个 Activity 和两个 fragment 。该应用程序使用带有容器的布局,因此 fragment 是通过事务添加的。第一个 fragment 包含一个 ListView ,另一个 fragment 包含 ListView 项的详细 View 。两个 fragment 都使用 setRetainInstance(true)。通过替换事务添加 fragment 并设置 addToBackStack(null)。 listfragment 包含一个实例变量,其中包含列表的一些信息。现在我要更改为详细信息并按回,实例变量为空。我阅读了 setRetainInstance 和 addToBackStack 并删除了 addToBackStack,但即便如此,实例变量仍为空。

有谁知道我可能做错了什么?

问候,托马斯

最佳答案

setRetainInstance(true) 将告诉 FragmentManager 在包含的 Activity 因某种原因被终止和重建时保留 fragment 。它不保证 Fragment 实例会在添加或替换事务后继续存在。听起来您的适配器正在被垃圾回收,而您并没有创建新适配器。

一个更简单的解决方案是制作一个无 View 的 Fragment 来保留您的 ListAdapter。您这样做的方法是创建 Fragment,将 retain 实例设置为 true,并在 onCreateView() 方法中返回 null。要添加它,只需通过 FragmentTransaction 调用 addFragment(Fragment, String)。您永远不会删除或替换它,因此它会在应用程序运行期间始终保留在内存中。屏幕旋转不会杀死它。

每当创建 ListFragment 时,在 onCreateView() 中获取 FragmentManager 并使用方法 findFragmentById()FindFragmentByTag() 从内存中检索您保留的 fragment 。然后从该 fragment 中获取适配器并将其设置为列表的适配器。

public class ViewlessFragment extends Fragment {

public final static string TAG = "ViewlessFragment";

private ListAdapter mAdapter;

@Override
public ViewlessFragment() {
mAdapter = createAdater();
setRetainInstance(true);
}

@Override
public void onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return null;
}

public ListAdapter getAdapter() {
return mAdapter;
}
}

public class MyListFragment extends ListFragment {

final public static String TAG = "MyListFragment";

@Override
public void onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View returnView = getMyView();
final ViewlessFragment adapterFragment = (ViewlessFragment) getFragmentManager().findFragmentByTag(ViewlessFragment.TAG);
setListAdapter(ViewlessFragment.getAdapter());
return returnView;
}
}

public class MainActivity extends FragmentActivity {

@Override
public void onCreate(Bundle icicle) {
// ... setup code...
final FragmentManager fm = getSupportFragmentManager();
final FragmentTransaction ft = fm.beginTransaction();
ViewlessFragment adapterFragment = fm.findFragmentByTag(ViewlessFragment.TAG);
if(adapterFragment == null) {
ft.add(new ViewlessFragment(), ViewlessFragment.TAG);
}
ft.add(R.id.fragmentContainer, new MyListFragment(), MyListFragment.TAG);
ft.commit();
}
}

关于android - 一个 Activity,多个 Fragments 和 setRetainInstance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14380234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com