我目前在我的类中扩展了ListFragment
,并使用以下解决方案:
1)在你的类的onActivityCreated
方法中检查你的适配器(它是一个类变量)是否为空,如果是,则实例化它。然后,像这样填充页脚:
View footerView = View.inflate
(getActivity(), R.layout.list_footer_loader_view, null)
你只需要做一次!footerView和adapter只需要创建一次。我在我的onActivityCreated
中创建了它们两个。
现在是“难点”了,将你的fragment在onCreate中设置为如下:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
我喜欢在onCreate
中完成它,因为它与活动无关。现在使用setRetainInstance(true)
后,当活动被销毁时,例如屏幕方向发生变化,您的片段将不会重新创建。
现在,在这些行之后添加页脚,如下所示:
getListView().addFooterView(footerView)
然后将适配器连接到列表:
setListAdapter(adapter)
每次活动结束时都应该完成此操作,可在onActivityCreated
中执行。
当涉及到片段时,另一个重要的事情是你不应该在每次活动的onCreate
被调用时都创建片段。
例如,如果您没有使用SupportPackage,则可以执行以下操作:
MyFragment myFragment = (MyFragment)
getFragmentManager().findFragmentByTag(tag);
if (myFragment == null) {
myFragment = MyFragment.newInstance();
getFragmentManager().beginTransaction().
add(myFragment, tag).commit();
}
如果该标签对应的片段是唯一的,那么这将只创建一次该片段。
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle){ View v = inflater.inflate(R.layout.fragment_pager_list, container,false); View tv = v.findViewById(R.id.text); ((TextView)tv).setText("Contacts"); return v; }
- Naveen Chauhanthis.setListAdapter(null); mAdapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_1, null, new String[] {ContactsContract.Contacts.DISPLAY_NAME}, new int[] { android.R.id.text1}, 0); this.setListAdapter(mAdapter); getLoaderManager().initLoader(0, null, this); }`
- Naveen Chauhan