屏幕旋转后恢复FragmentActivity

时间:2013-05-16 11:53:16

标签: android android-fragments android-viewpager android-fragmentactivity viewpagerindicator

我正在使用Jake Wharton的ViewPagerIndicator库,在下面显示的FragmentActivity中,当我旋转屏幕时调用onCreate方法,但活动仍然是空白的,只显示指示符('Tab 1'和'Tab 2')。 / p>

public class MainActivity extends FragmentActivity {

    private static final String[] CONTENT = new String[] { "Tab 1", "Tab 2", };

    ProgressDialog progress;

    FragmentPagerAdapter adapter;
    ViewPager pager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        progress = ProgressDialog.show(this, "Loading", "Loading data...");

        new getData().execute();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);

    }

    class FragPagerAdapter extends FragmentPagerAdapter {
        public FragPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if(position == 0){
                return FragmentTabOne.newInstance();
            }else if(position == 1){
                return FragmentTabTwo.newInstance();
            }
            return null;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return CONTENT[position % CONTENT.length].toUpperCase();
        }

        @Override
        public int getCount() {
            return CONTENT.length;
        }

    }

    private class getData extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {

            //getting data from server

            return true;
        }

        protected void onPostExecute(final Boolean success) {

                setContentView(R.layout.main_activity); //indicator + viewpager

                adapter = new FragPagerAdapter(getSupportFragmentManager());

                pager = (ViewPager)findViewById(R.id.pager);

                pager.setAdapter(adapter);

                TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
                indicator.setViewPager(pager);

                progress.dismiss();

            }
        }

    }
}

我应该怎样做(可能在onSaveInstanceState方法中),以便正确显示活动及其片段?感谢

1 个答案:

答案 0 :(得分:1)

在您的片段“onCreateView()尝试添加对setRetainInstance(true)

的调用