2

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

我的代码如下:

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

1 回答 1

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;
}
于 2013-02-12T15:34:17.363 回答