我无法让我的 Fragment 在方向更改时保留其实例。
活动课
public class MyActivity extends Activity
{
private MyFragment fragment;
public void onCreate(Bundle savedInstanceState)
{
if(savedInstanceState == null)
{
fragment = new MyFragment();
}
//null pointer exception on this line of code. fragment not being retained.
getFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
}
}
片段类
public class MyFragment extends Fragment
{
private View view;
private CustomListViewAdapter adapter;
public ArrayList<HashMap<String, String>> arrHashMap;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_screen, container, false);
if(arrHashMap != null)
{
ListView lv = (ListView) view.findViewById(R.id.fragment_lv);
adapter = new CustomListViewAdapter( (MyActivity)getActivity() , arrHashMap);
lv.setAdapter(adapter);
lv.setOnItemClickListener((MyActivity)getActivity());
}
else
{
/* some code to create arrHashMap variable
*/
ListView lv = (ListView) view.findViewById(R.id.fragment_lv);
adapter = new CustomListViewAdapter( (MyActivity)getActivity() , arrHashMap);
lv.setAdapter(adapter);
lv.setOnItemClickListener((MyActivity)getActivity());
}
return(view);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}
尽管在 onActivityCreated 中设置了 setRetainInstance(true),但 MyFragment 在方向更改时仍为空。创建 MyActivity 时,也会始终重新创建 MyFragment。另外,我知道 setRetainInstance(true) 不适用于 UI 片段,但是,我没有使用保存的适配器或视图成员变量,我只是在方向更改时重用保留的 arrHashMap 变量,因此我可以重新创建适配器并更改用户界面。