我在另一个片段的左侧有一个列表片段,本质上是标准的单击项目并更新右侧片段模式。当他们单击列表片段中的一个项目时,他们正在选择新闻文章类别,我需要在他们旋转设备时保留选择的任何一个。我怎么做?我当前的代码不起作用。
我的代码如下:
public class SideMenuFragment extends ListFragment {
ArrayList<SideItem> sideItems;
SideAdapter sideAdapter;
public SideMenuFragment() {
this.setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.list, null);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
sideItems = new ArrayList<SideItem>();
...add bunch of items
sideAdapter = new SideAdapter(getActivity(), sideItems);
getListView().setVerticalScrollBarEnabled(false);
setListAdapter(sideAdapter);
if (savedInstanceState != null) {
sideAdapter.setSelectedItem(savedInstanceState.getInt("sidePosition"));
sideAdapter.notifyDataSetChanged();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("sidePosition", sideAdapter.getSelectedItem());
}
@Override
public void onListItemClick(ListView lv, View v, int position, long id) {
if (sideAdapter.getSelectedItem() != position) {
sideAdapter.setSelectedItem(position);
sideAdapter.notifyDataSetChanged();
}
switch (position) {
...switch the fragment depending on position.
}
}
// the meat of switching the above fragment
private void switchFragment(Fragment fragment, String title) {
if (getActivity() == null)
return;
if (getActivity() instanceof HomeActivity) {
HomeActivity a = (HomeActivity) getActivity();
a.switchContent(fragment, title);
}
}
}