Android保存动态添加了viewpager的片段,同时从另一个活动返回并重新打开应用程序

时间:2015-11-16 05:28:48

标签: android android-fragments

在StackOverflow(DEMO)的回答中,我成功创建了我的项目,并根据我的需要进行了一些修改。

我可以在主布局中添加N个片段(viewpages)并删除它们,直到页数变为零。

现在,我遇到了一个问题。其中一个,如果我从当前活动中移动这个页面到其他活动,或者如果我关闭我的应用程序然后回来,我只能看到最初的静态添加片段。

我不仅希望看到初始页面,还希望看到之前添加的页面。我应该使用SharedPreferences存储动态添加的片段吗?

这是我的源代码: 我的主要布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     >

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="900dp"
      />

     <Button
        android:id="@+id/show_items"
        android:layout_width="40dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="200dp"
      android:textColor="#ffffff"
      android:background="#49a942"
      android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:text="+" />
    <Button 
        android:id="@+id/grid_apps_show"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/pager"
        android:layout_alignParentBottom="true"
        android:text="Apps"
        />

</RelativeLayout>

我的MainActivity类:

public class MainActivity extends FragmentActivity implements TextProvider{
    Button home;
    private ViewPager mPager;

    private MyPagerAdapter mAdapter;

    private ArrayList<String> mEntries = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        home = (Button) findViewById(R.id.show_items);

        mEntries.add("pos 1");

        mPager = (ViewPager) findViewById(R.id.pager);
        home.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        MainActivity.this);

                    alertDialogBuilder.setTitle("Add/Delete Screens");

                    alertDialogBuilder
                        .setCancelable(false)
                        .setNegativeButton("+",new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                addNewItem();
                            }
                          })
                        .setPositiveButton("-",new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                removeCurrentItem();
                            }
                        });

                        // create alert dialog
                        AlertDialog alertDialog = alertDialogBuilder.create();

                        // show it
                        alertDialog.show();




                        }
        });
        mAdapter = new MyPagerAdapter(this.getSupportFragmentManager(), this);
        mPager.setAdapter(mAdapter);


                    }
    private void addNewItem() {
            mEntries.add("Pages");
            mAdapter.notifyDataSetChanged();
        }
    private void removeCurrentItem() {
        int position = mPager.getCurrentItem();
        if(position != 0){
        mEntries.remove(position);
        mAdapter.notifyDataSetChanged();
       }
        else{
            Toast.makeText(getApplicationContext(), "Minimum Screens are one!", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public String getTextForPosition(int position) {
        return mEntries.get(position);
    }
    @Override
    public int getCount() {
        return mEntries.size();
    }


    private class MyPagerAdapter extends FragmentPagerAdapter {

        private TextProvider mProvider;
        private long baseId = 0;

        public MyPagerAdapter(FragmentManager fm, TextProvider provider) {
            super(fm);
            this.mProvider = provider;
        }

        @Override
        public Fragment getItem(int position) {
            if(position == 0){
                return ScreenOne.newInstance(mProvider.getTextForPosition(position));   
            }
            if(position == 1){
                return ScreenTwo.newInstance(mProvider.getTextForPosition(position));
            }


            return ScreenTwo.newInstance(mProvider.getTextForPosition(position));
        }

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


        //this is called when notifyDataSetChanged() is called
        @Override
        public int getItemPosition(Object object) {
            // refresh all fragments when data set changed
            return PagerAdapter.POSITION_NONE;
        }


        @Override
        public long getItemId(int position) {
            // give an ID different from position when position has been changed
            return baseId + position;
        }

        /**
         * Notify that the position of a fragment has been changed.
         * Create a new ID for each position to force recreation of the fragment
         * @param n number of items which have been changed
         */
        public void notifyChangeInPosition(int n) {
            // shift the ID returned by getItemId outside the range of all previous fragments
            baseId += getCount() + n;
        }
    }
}

my fragment one:
public class ScreenOne  extends Fragment {

    private String mText;

    public static ScreenOne newInstance(String text) {
        ScreenOne f = new ScreenOne(text);
        return f;
    }

    public ScreenOne() {
    }

    public ScreenOne(String text) {
        this.mText = text;
    }

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

        View root = inflater.inflate(R.layout.screen_one, container, false);

        ((TextView) root.findViewById(R.id.position_one)).setText(mText);

        return root;
    }

}

my fragment two:
public class ScreenTwo  extends Fragment {

    private String mText;

    public static ScreenTwo newInstance(String text) {
        ScreenTwo f = new ScreenTwo(text);
        return f;
    }

    public ScreenTwo() {
    }

    public ScreenTwo(String text) {
        this.mText = text;
    }

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

        View root = inflater.inflate(R.layout.screen_two, container, false);

        ((TextView) root.findViewById(R.id.position_two)).setText(mText);

        return root;
    }

}

谢谢&amp;问候, 阿迪亚。 Ĵ

1 个答案:

答案 0 :(得分:2)

只需在FragmentpagerAdapter中重写此方法:

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    super.destroyItem(ViewGroup container, int position, Object object);
}

并删除:

super.destroyItem(ViewGroup container, int position, Object object);