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



在StackOverflow(Android中的Remove Fragment Page from ViewPager)中这个问题的答案的帮助下,我成功地创建了我的项目,并根据我的需求进行了一些修改。

我可以在我的主布局中添加N个片段(视图页面),然后删除它们,直到页面数变为零。

现在,我遇到了一个问题。即,如果我从当前的活动(保存此页面)转移到其他活动,或者如果我关闭应用程序并返回,我只能看到初始静态添加的片段。

我不仅想看到初始页面,还想看到以前添加的页面。我应该使用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>

我的主要活动类:

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;
    }
}

谢谢&当做Aditya。J

只需在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);

最新更新