Android 在viewpager中保存和恢复片段状态

Android 在viewpager中保存和恢复片段状态,android,android-fragments,fragmentpageradapter,Android,Android Fragments,Fragmentpageradapter,这可能是一个重复的问题,但似乎没有一个答案可以解决我的问题。因此,我有一个类,它可以extendsViewPager,在水平导航中,我有3个页面。在Fragment的onActivityCreated()方法中,我正在调用服务器,获取一些数据并将TableRow插入TableLayout中。现在我想保存这个确切的状态,并在导航回相同的片段时将其还原 我注意到的一件奇怪的事情是,当我从一个选项卡滑动到下一个选项卡,然后再滑动到第一个选项卡时,第一个选项卡的状态没有变化。然而,在从第一个导航到第二个

这可能是一个重复的问题,但似乎没有一个答案可以解决我的问题。因此,我有一个类,它可以
extend
s
ViewPager
,在水平导航中,我有3个页面。在
Fragment
onActivityCreated()
方法中,我正在调用服务器,获取一些数据并将
TableRow
插入
TableLayout
中。现在我想保存这个确切的状态,并在导航回相同的
片段时将其还原

我注意到的一件奇怪的事情是,当我从一个
选项卡
滑动到下一个选项卡,然后再滑动到第一个选项卡时,第一个
选项卡
的状态没有变化。然而,在从第一个导航到第二个导航到第三个导航,然后返回到第一个导航时,我失去了状态。除了使用
onSaveInstanceState()
之外,是否有其他方法保存
片段的状态,然后在以后还原它?因为这需要我手动将所有数据存储在
包中。这是我的
片段

public static class ProfileFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

        View fragmentView = inflater.inflate(R.layout.fragment_profile, container, false);
        return fragmentView;
    }

    private final int EMPLOYER_TABLE_ROWS = 3;
    private final int STUDENT_TABLE_ROWS = 7;
    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);

        HasuraClient client = Hasura.getClient();

        // make network calls to fetch data from server

        HasuraUser user = client.getUser();
        String[] role = user.getRoles();

        if(role[1].equals(getString(R.string.student_role).toLowerCase())){
            StudentProfileQuery query = new StudentProfileQuery(user.getId());
            client.asRole(getString(R.string.student_role).toLowerCase()).useDataService()
                    .setRequestBody(query)
                    .expectResponseType(ProfileResponse.class)
                    .enqueue(new Callback<ProfileResponse, HasuraException>() {
                        @Override
                        public void onSuccess(ProfileResponse response) {
                            // Handle response

                            // get headingContainer
                            LinearLayout headingContainer = (LinearLayout) getView().findViewById(R.id.name_and_institute);
                            // get inflater object
                            LayoutInflater inflater = LayoutInflater.from(getContext());

                            // place name
                            TextView headingName = (TextView) inflater.inflate(R.layout.profile_page_title, headingContainer, false);
                            headingName.setText(response.getName());
                            headingContainer.addView(headingName, 0);

                            // place instituteName
                            TextView headingInstitution = (TextView) inflater.inflate(R.layout.profile_page_title, headingContainer, false);
                            headingInstitution.setText("Student" + " at " + response.getInstitution());
                            headingContainer.addView(headingInstitution, 1);

                            String[] field = {"Email", "Date Of Birth", "Gender", "Year of Admission", "Year of Passing", "Percentage",
                                    "Resume URL"};
                            String[] detail = {response.getEmail(), response.getDob(), response.getGender(),
                                    response.getYear_of_admission().toString(), response.getYear_of_passing().toString(),
                                    response.getPercentage().toString(), response.getPath_to_cv()};

                            // insert TableRows in TableLayout
                            // get TableLayout container
                            TableLayout tableContainer = (TableLayout) getView().findViewById(R.id.profile_table);

                            for(int i = 0; i < STUDENT_TABLE_ROWS; i++){
                                // inflate TableRow
                                TableRow row = (TableRow) inflater.inflate(R.layout.profile_page_table, tableContainer, false);

                                // inflate element of col0 and set field, width
                                TextView col0Element = (TextView)inflater.inflate(R.layout.profile_table_row_element, row, false);
                                col0Element.setLayoutParams(new ViewGroup.LayoutParams(R.dimen.profile_col_0, ViewGroup.LayoutParams.WRAP_CONTENT));
                                col0Element.setText(field[i]);

                                // inflate element of col1 and set detail, width
                                TextView col1Element = (TextView)inflater.inflate(R.layout.profile_table_row_element, row, false);
                                col1Element.setLayoutParams(new ViewGroup.LayoutParams(R.dimen.profile_col_1, ViewGroup.LayoutParams.WRAP_CONTENT));
                                col1Element.setText(detail[i]);

                                // add col0 element to TableRow
                                row.addView(col0Element, 0);

                                // add col1 element to TableRow
                                row.addView(col1Element, 1);

                                // add TableRow to TableLayout
                                tableContainer.addView(row, i);
                            }
                        }

                        @Override
                        public void onFailure(HasuraException e) {
                            //Handle error
                            Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
        }

        else if(role[1].equals(getString(R.string.employer_role).toLowerCase())){
            EmployerProfileQuery query = new EmployerProfileQuery(user.getId());
            client.asRole(getString(R.string.employer_role).toLowerCase()).useDataService()
                    .setRequestBody(query)
                    .expectResponseType(ProfileResponse.class)
                    .enqueue(new Callback<ProfileResponse, HasuraException>() {
                        @Override
                        public void onSuccess(ProfileResponse response) {
                            // Handle response

                            // get headingContainer
                            LinearLayout headingContainer = (LinearLayout) getView().findViewById(R.id.name_and_institute);
                            // get inflater object
                            LayoutInflater inflater = LayoutInflater.from(getContext());

                            // place name
                            TextView headingName = (TextView) inflater.inflate(R.layout.profile_page_title, headingContainer, false);
                            headingName.setText(response.getName());
                            headingContainer.addView(headingName, 0);

                            // place company name and designation
                            TextView headingCompany = (TextView) inflater.inflate(R.layout.profile_page_title, headingContainer, false);
                            headingCompany.setText(response.getDesignation() + " at " + response.getCompany());
                            headingContainer.addView(headingCompany, 1);

                            String[] field = {"Name", "Email", "Date Of Birth", "Gender"};
                            String[] detail = {response.getName(), response.getEmail(), response.getDob(), response.getGender()};

                            // insert TableRows in TableLayout
                            // get TableLayout container
                            TableLayout tableContainer = (TableLayout) getView().findViewById(R.id.profile_table);

                            for(int i = 0; i < EMPLOYER_TABLE_ROWS; i++){
                                // inflate TableRow
                                TableRow row = (TableRow) inflater.inflate(R.layout.profile_page_table, tableContainer, false);

                                // inflate element of col0 and set field, width
                                TextView col0Element = (TextView)inflater.inflate(R.layout.profile_table_row_element, row, false);
                                col0Element.setLayoutParams(new ViewGroup.LayoutParams(R.dimen.profile_col_0, ViewGroup.LayoutParams.WRAP_CONTENT));
                                col0Element.setText(field[i]);

                                // inflate element of col1 and set detail, width
                                TextView col1Element = (TextView)inflater.inflate(R.layout.profile_table_row_element, row, false);
                                col1Element.setLayoutParams(new ViewGroup.LayoutParams(R.dimen.profile_col_1, ViewGroup.LayoutParams.WRAP_CONTENT));
                                col1Element.setText(detail[i]);

                                // add col0 element to TableRow
                                row.addView(col0Element, 0);

                                // add col1 element to TableRow
                                row.addView(col1Element, 1);

                                // add TableRow to TableLayout
                                tableContainer.addView(row, i);
                            }
                        }

                        @Override
                        public void onFailure(HasuraException e) {
                            //Handle error
                            Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

    }
}
除此之外,还有另外两个
Fragment
s,我认为没有必要发布它们的代码。
提前谢谢

使用
mviewpage.setOffscreenPageLimit(noOfPageYouWantToKeepInMemory)

我只希望一个
片段
在整个活动生命周期中保留其信息,而另外两个则希望每次显示时都从服务器动态获取其数据。请尝试以下操作:在FragmentpagerAdapter@override public void destroyItem中重写此方法(ViewGroup容器,int位置,Object对象){//TODO自动生成的方法存根super.destroyItem(ViewGroup容器,int位置,Object对象);}从代码中删除super.destroyItem(ViewGroup容器,int位置,Object对象)
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a UI (defined as a static inner class below).
        switch(position){
            case 0:
                return new ProfileFragment();

            case 1:
                return new MessagesFragment();

            case 2:
                return new HomeFragment();
        }

        return null;
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return getString(R.string.profile_tab);
            case 1:
                return getString(R.string.messages_tab);
            case 2:
                return getString(R.string.home_tab);
        }
        return null;
    }
}