保持列表片段在方向更改时选择项目位置

时间:2013-02-12 15:22:51

标签: android android-fragments

我在另一个片段的左边有一个列表片段,基本上是标准点击一个项目并更新正确的片段模式。当他们点击列表片段中的项目时,他们正在选择新闻文章类别,我需要保留旋转设备时选择的任何内容。我怎么做?我目前的代码不起作用。

我的代码如下:

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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

首先,如果Activity布局,请在xml中添加Fragment。 在Activity onCreate

getFragmentManager().findFragmentById(R.id.youtfragmentid).setRetainInstance(true)

这意味着不会在重新创建活动时重新创建片段。

不要在onActivityCreated中更改ListView - 因为每次方向更改时都会重建它。如果您设置了新的适配器 - 将重置子项的状态。

添加检查null或已创建视图的布尔标志。 下次调用onActivityCreated时,列表适配器不应更改

if (sideAdapter == null) {

    sideAdapter = new SideAdapter(getActivity(), sideItems);
        getListView().setVerticalScrollBarEnabled(false);
        setListAdapter(sideAdapter);

}

另外,不要在onCreateView中创建新视图,而是使用之前创建的视图。

private View v;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    if (v == null) {
        v = inflater.inflate(R.layout.list, null);
    } else {
        // detatch from container and return the same view
        ((ViewGroup) getListView().getParent()).removeAllViews();
    }
    return v;
}