Hy,我的片段中有列表视图。我用我的其他片段替换这个listview片段但是当我想要回到我的列表时,它是空的。我以为我可以恢复我的列表项目,但我不知道如何。我假设与Fragment生命周期一致,我的适配器将是可重用的,但看起来并非如此。这是我的代码:
public class ThreadListFragment extends Fragment implements FragmentConnectionStatus, ListFragment, OnClickListener, OnItemClickListener{
private ListView ListView;
private PilotController Activity;
private Button ButtonStartNewThread;
private boolean Paused;
private ThreadInfoAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
/**
* Inflate the layout for this fragment
*/
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.threads_list_fragment, container, false);
System.out.println(this.Paused);
if(this.Paused == false){
this.ListView = (ListView) view.findViewById(R.id.listViewActiveThreads);
ArrayList<Guid> strs = new ArrayList<Guid>();
adapter = new ThreadInfoAdapter(view.getContext(), strs, this);
}
this.ListView.setAdapter(adapter);
this.ListView.setItemsCanFocus(true);
this.ListView.setOnItemClickListener(this);
this.Activity = (PilotController) getActivity();
this.ButtonStartNewThread = (Button) view.findViewById(R.id.buttonStartThread);
this.ButtonStartNewThread.setOnClickListener(this);
return view;
}
@Override
public void onPause()
{
super.onPause();
this.Paused = true;
}
但是当我回到我的旧名单时,它是空的。你能给我一些建议吗?
解
我找到了解决方案。 ListView可能正在从'draw stack'中删除所以当调用OnDeleteView时,你的旧列表下次无法使用,尽管仍然设置了对该对象的引用。解决方案是重新创建ListView并设置旧适配器。由于本教程http://developer.android.com/guide/components/fragments.html,此适配器将继续存在,但视图被重新创建(因此旧的listview不再存在(它存在但它不可绘制)。我不得不改变这一行:
if(this.Paused == false){
this.ListView = (ListView) view.findViewById(R.id.listViewActiveThreads);
ArrayList<Guid> strs = new ArrayList<Guid>();
adapter = new ThreadInfoAdapter(view.getContext(), strs, this);
}
为:
this.ListView = (ListView) view.findViewById(R.id.listViewActiveThreads);
if(this.Paused == false){
ArrayList<Guid> strs = new ArrayList<Guid>();
adapter = new ThreadInfoAdapter(view.getContext(), strs, this);
}
答案 0 :(得分:0)
在“onActivityCreated”中你可以检查你的dataList(在你的情况下是“strs”)是否为空。如果不是,那么只需使用它,否则创建一个新的。在代码中它看起来像这样:
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (strs == null)
strs = new ArrayList<Guid>();
mListView = (ListView)getActivity().findViewById(R.id.listViewActiveThreads);
mPersonAdapter = new ArrayAdapterPerson(getActivity(),mPersonList,this);
mListView.setAdapter(mPersonAdapter);
}
答案 1 :(得分:0)
我在这里找到了我的解决方案:ListFragment is empty after going back
使用transaction.hide(this):
ft.addToBackStack(null);
ft.hide(this);
ft.add(R.id.frag_frame, lyrics);
ft.commit();