Android 在从另一个 Activity 返回并重新打开应用程序时保存动态添加的 viewpager 的 fragment

标签 android android-fragments

借助StackOverflow( Remove Fragment Page from ViewPager in Android )中这个问题的回答,我成功地创建了我的项目,并根据我的需要做了一些修改。

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

现在,我遇到了一个问题,即那些,如果我从持有此页面的当前 Activity 转移到其他 Activity ,或者如果我关闭我的应用程序并返回,我只能看到初始静态添加的 fragment 。

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

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

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

}

感谢和问候, 阿迪亚。 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);

关于Android 在从另一个 Activity 返回并重新打开应用程序时保存动态添加的 viewpager 的 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33729038/

相关文章:

java - IntentServices 会占用应用程序内存吗?

Android OpenCV : update camera frames while executing AsyncTask

android - 如何使用导航组件获取上一个目的地?

android - 从 ActionBar 选项卡获取当前 fragment

Android:无法在 fragment 中设置 TextView 值

android - 如何正确处理嵌套 fragment 中的 MaskedWallet 响应

android - resValue 梯度错误 : Unsupported type "String" in "generated.xml"

Android:在应用计费中,是否使用库?

android - 使用 Android SDK 从 BB10 发送短信

android - 使用 add() 方法添加 fragment 不会隐藏以前的 fragment