我正面临着关于片段的问题。 在我的场景中,
FragmentActivity有两个片段。 在FragmentActivity中,有一个容器布局(Frame Layout),其中所有片段都将替换。
public void replaceFragment(Fragment fragmentClass) {
String selectedFragment = fragmentClass.getClass().getName();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction
.replace(R.id.content_frame, fragmentClass);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
第一次,我设置了一个List类型片段(片段A),其中从Web服务获取数据并在listview上进行填充。我从onCreateView()方法执行AsyncTask。
在MainActivity中:onCreate
SherlockFragment fragment = new FragmentA();
replaceFragment(fragment);
在列表项上单击片段A,片段A将回调活动方法以将其替换为详细信息类型片段片段B。
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
callback = (ICallBack) activity;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/*View rootView = inflater.inflate(R.layout.fragment_locate, container,
false);*/
View rootView = inflater.inflate(R.layout.fragment_a, container,
false);
ListView list = (ListView) rootView
.findViewById(R.id.listView);
adapter = new MyListAdapter();
list.setAdapter(adapter);
list
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View convertView, int position, long id) {
SherlockFragment fragment = new SalonDetailFragment();
callback.replaceFragment(fragment);
}
});
ListDataTask task = new ListDataTask();
task.execute();
return rootView;
}
class ListDataTask extends AsynTask<Void,Void,List<Data>>{
public Void doInBackground(Void parems){
List<Data> = getDataFromServer();
}
onPostExecute(List<Data> data){
adapter.addAllData(data);
adapter.notifyDataSetChanged();
}
}
当我按下后退按钮时,从片段B然后应用程序将显示片段A但它再次执行Asynctask并获取数据以表示列表视图。
所以我需要知道,如何保持像活动一样的片段的过去状态。
从其他活动回来后,有没有办法不创建片段
看看我的伪代码。
答案 0 :(得分:6)
我得到了解决方案。简单....执行rootview
的check null值public class FragmentA extends Fragment {
View _rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (_rootView == null) {
// Inflate the layout for this fragment
_rootView = inflater.inflate(R.layout.fragment_a, container, false);
// Find and setup subviews
_listView = (ListView)_rootView.findViewById(R.id.listView);
...
} else {
// Do not inflate the layout again.
// The returned View of onCreateView will be added into the fragment.
// However it is not allowed to be added twice even if the parent is same.
// So we must remove _rootView from the existing parent view group
// (it will be added back).
((ViewGroup)_rootView.getParent()).removeView(_rootView);
}
return _rootView
答案 1 :(得分:5)
我有同样的问题,并通过替换
解决 fragmentTransaction
.replace(R.id.content_frame, fragmentClass);
to
fragmentTransaction
.add(R.id.content_frame, fragmentClass);
替换将始终在后退时创建新实例,而添加只是在堆栈中添加新片段。有关详细信息,请查看此link