在具有ViewPager的片段中保存ListView选定的项目

时间:2014-01-13 11:52:42

标签: android android-listview android-fragments android-viewpager

我正在尝试制作某种测试应用,您可以将其从一个问题更改为另一个向左或向右滑动。所以,我有一个FragmentActivity,一个ViewPager和一个FragmentPagerAdapter。

每个新页面FragmentPagerAdapter使用相同的布局实例化一个新的片段,其中有一个ListView,最多5页。然后,ArrayAdapter用4个CheckedTextViews填充ListView,当用户选择一个时,背景会发生变化。

问题在于,当您从一个问题滑动到另一个问题时,所选项目将丢失,当用户滑回上一个问题时,该项目将不再被选中。

我是片段的新手,但是当我使用从xml直接膨胀的复选框执行相同操作时,他们选择的状态在滑动时不会丢失。

以下是一些代码:

FragmentActivity onCreate():

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        //Getting the array of questions.
        res = getResources();
        questions = res.getStringArray(R.array.questions_1);

        // Create the adapter that will return a fragment for each of the five
        // questions of the app.
        mAdapter = new MyAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the FragmentPagerAdapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setOffscreenPageLimit(10);
        mViewPager.setAdapter(mAdapter);
    }

FragmentPagerAdapter:

    public class MyAdapter extends FragmentPagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);

    }

    @Override
    public int getCount() {
            //Number of pages
    return 5;
    }

    @Override
    public Fragment getItem(int position) {
        ArrayListFragment fragment = ArrayListFragment
                .newInstance(position);

        return fragment;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();

        return getString(R.string.title_section) + " " + (position + 1);

    }
}

片段类:

public static class ArrayListFragment extends Fragment {
            //Current Page number.
    int mNum;
    public static final String ARG_SECTION_NUMBER = "section_number";
    ListView list;

    /**
     * Create a new instance of ArrayListFragment, providing "num" as an
     * argument.
     */
    static ArrayListFragment newInstance(int num) {
        ArrayListFragment f = new ArrayListFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;

    }

    /**
     * The Fragment's UI is a textview showing a question and the ListView with               
             * the four possible answers.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_pager_list, container,
                false);
        View tv = v.findViewById(R.id.text);
                    //Set the Question
        ((TextView) tv).setText(questions[mNum]);
        //Get que ListView and fill it.
        list = (ListView) v.findViewById(R.id.listView1);
        list.setAdapter(new ArrayAdapter<String>(getActivity(),
                R.layout.list_item, myStringArray));
                    //Select an item.
        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                arg1.setSelected(true);
            }

        });


        return v;
    }


}

2 个答案:

答案 0 :(得分:0)

实际上它不应该记住你的选择。一旦你离开页面,它可能会被销毁。默认情况下,ViewPager仅保存3页(当前一页,左侧和右侧)。但您可以保存用户选择主机活动。为此,您需要创建一个界面,比如函数public void onAnswerSelected(int questionId, int answerId),并在Activity中实现它。在片段覆盖onAttach函数中,巫婆具有作为参数的活动。将其保存为类成员,您可以回调活动。用户选择接听电话callback.onAnswerSelected(questionId, answerId)后。要恢复以前的状态,请在界面中添加其他功能getSavedAnswer(int questionId)当您在onActivityCreated()时调用它。现在,您需要HashMap中的Activity个答案,以便节省答案。

答案 1 :(得分:0)

使用复选框进行布局恢复是合理的。如果有一个android:id属性,片段可以恢复布局中的视图状态。但是你的listView没有恢复状态,这取决于你实现的适配器。您必须手动执行此操作,例如:在Fragment的onSaveInstanceState中保存listView中的选择状态,然后从savedInstanceState中获取您的选择,就像在Activity中一样。