使用FragmentPagerAdapter保存Fragment的状态

时间:2016-05-10 13:55:34

标签: android android-fragments

我创建了一个FragmentPagerAdapter来显示许多带有相同片段的问题。

这是片段:

QuestionFragment

当给出答案并验证时,我禁用按钮和EditText。 但是当我滑动两个Fragment并返回到此时,EditText和Button不再禁用,用户可以更改编辑文本的值。

这是FragmentPagerAdapter:

    /**
     * A simple {@link Fragment} subclass.
     */
    public class PlayFragment extends FragmentPagerAdapter {

        //--Jouer un circuit
        private static Game currentGame = null; //La partie courante
        public static Circuit circ;
        private static List<QuestionReponse> questionsReponses = new ArrayList<>();

        private int PAGE_COUNT;
        private static ArrayList<String> listTitles = new ArrayList<>();

        public PlayFragment(FragmentManager fm) {
            super(fm);
            this.listTitles = new ArrayList<>();
            for (int i = 0; i < currentGame.getDifficulties().size(); i++) {
                this.listTitles.add(currentGame.getDifficulties().get(i).getName()); //Les difficultées choisis
            }
            this.PAGE_COUNT = currentGame.getDifficulties().size();
        }


        @Override
        public int getCount() {
            return PAGE_COUNT;
        }

        @Override
        public Fragment getItem(int position) {
            return QuestionFragment.newInstance(position + 1);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            // Generate title based on item position
            return listTitles.get(position);
        }

        public static Game getCurrentGame() {
            return currentGame;
        }

        public static void setCurrentGame(Game currentGame) {
            PlayFragment.currentGame = currentGame;
        }


        public static ArrayList<String> getListTitles() {
            return listTitles;
        }

        public static void setListTitles(ArrayList<String> listTitles) {
            PlayFragment.listTitles = listTitles;
        }
    }

这是StartGameFragment:

/**
 * A simple {@link Fragment} subclass.
 */
public class StartGameFragment extends Fragment implements AsyncResponse {

    PlayFragment playFragment;

    public StartGameFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        ((MainActivity) getActivity()).changeActionBarTitle(getString(R.string.nav_circuit_dl));
        MenuItem item = ((MainActivity) getActivity()).navigationView.getMenu().findItem(R.id.nav_dl_circuit);
        if (item != null) item.setChecked(true);

        //Allow to modify ActionBar menu in this fragment
        setHasOptionsMenu(true);
        //new JSONGetter().execute("");
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_start_game, container, false);

        ViewPager viewPager = (ViewPager) v.findViewById(R.id.viewpager);
        this.playFragment = new PlayFragment(getActivity().getSupportFragmentManager());
        viewPager.setAdapter(playFragment);

        // Give the TabLayout the ViewPager
        TabLayout tabLayout = (TabLayout) v.findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);
        return v;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
    }


    @Override
    public void onDestroyView() {
        MenuItem item = ((MainActivity) getActivity()).navigationView.getMenu().findItem(R.id.nav_dl_circuit);
        if (item != null) item.setChecked(false);
        super.onDestroyView();
    }

    @Override
    public void onTaskDBCompleted(String result, Object entity, String method) {

    }

    @Override
    public void onTaskCompleted(String result, String method) {

    }
}

最后是QuestionFragment(我不会显示所有内容,因为此片段中的代码太多):

/**
 * A simple {@link Fragment} subclass.
 */
public class QuestionFragment extends Fragment implements AsyncResponse {

    public QuestionFragment() {
        // Required empty public constructor
    }


    public static QuestionFragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, page);
        QuestionFragment fragment = new QuestionFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage = getArguments().getInt(ARG_PAGE);
    }
}

我尝试使用this solution,但这对我不起作用!

3 个答案:

答案 0 :(得分:1)

v4支持库中有另一个名为FragmentStatePagerAdapter的适配器。

默认情况下保存片段的内部状态。您也可以覆盖其saveState()restoreState()方法来保存/恢复自定义状态数据。

答案 1 :(得分:-1)

//将您的状态存储在片段

 @Override
 protected void onSaveInstanceState(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onSaveInstanceState(outState);

 String stateToSave = edittextEditState.getText().toString();
 savedInstanceState.putString("saved_state", stateToSave);
}

}

//检索数据

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState != null ) {
 Toast.makeText(this, savedInstanceState .getString("saved_state"),Toast.LENGTH_LONG).show();
 } 
 }

答案 2 :(得分:-1)

使用savedInstanceState

保存片段的状态

参考 - http://developer.android.com/training/basics/activity-lifecycle/recreating.html