ViewPager+Fragment动态增加页面,删除页面

项目中要使用viewPager同时要实现动态增加删除的效果。

首先实现viewPager和fragment的嵌套使用,在google的Android开发文档里有现成的例子:地址如下:

https://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html

例子里是固定的10个页面,现在开始实现动态增加页面的功能:(先讲过程代码,最后附完整代码)

1.在调用类里面实现一个Fragment列表用于增加、删除Fragment;

private ArrayList<Fragment> fragments = null;
fragments = new ArrayList<>();
2.在列表里面添加几个fragment。其中 ArrayListFragment.newInstance()是自定义的一个framgent类,这句话用于new一个新的实例fragment页面

fragments.add(ArrayListFragment.newInstance(1));
fragments.add(ArrayListFragment.newInstance(2));
fragments.add(ArrayListFragment.newInstance(3));
3.在自定义的Adaper里面定义保持fragment的list

private ArrayList<Fragment> fragments = null;
同时在构造函数里面添加一个ArrayList<Fragment> 的参数,用于把外面的fragment list 传递进来。

4.在调用类添加俩个函数,分别是添加页面和删除页面:添加和删除的原理是,通过改变list里面的fragment内容,并刷新adaper来实现动态增加,删除的功能

public void AddFragment() {
    fragments.add(ArrayListFragment.newInstance(5));
    mAdapter.notifyDataSetChanged();

}
public void DelFragment() {
    fragments.remove(fragments.size()-1);
    mAdapter.notifyDataSetChanged();
}
5.注意事项,要实现这一的功能需要几个注意事项:

(1)自定义的Adapter 要继承自 FragmentStatePagerAdaper

(2)自定义的Adapter 要重写 getItemPosition 函数:

  1.   @Override  
  2.     public int getItemPosition(Object object) {  
  3.         // TODO Auto-generated method stub  
  4.         return PagerAdapter.POSITION_NONE;  
  5.     } 
这里是参考了一篇博客的内容:地址如下:

http://blog.csdn.net/quanjin24k/article/details/17318151

动手实现了效果,所以总结一下,贴出完整代码,以方便大家快捷的使用:

以下为完整代码:

MainActivity.java

package com.robert.viewpagertest;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    static final int NUM_ITEMS = 10;

    MyAdapter mAdapter;

    ViewPager mPager;

    private ArrayList<Fragment> fragments = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragments = new ArrayList<>();
        fragments.add(ArrayListFragment.newInstance(1));
        fragments.add(ArrayListFragment.newInstance(2));
        fragments.add(ArrayListFragment.newInstance(3));



        mAdapter = new MyAdapter(getSupportFragmentManager(), fragments);

        mPager = (ViewPager)findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);

        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.goto_first);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //mPager.setCurrentItem(0);
                AddFragment();
            }
        });
        button = (Button)findViewById(R.id.goto_last);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               // mPager.setCurrentItem(NUM_ITEMS-1);
                DelFragment();
            }
        });
    }

    public void AddFragment() {
        fragments.add(ArrayListFragment.newInstance(5));
        mAdapter.notifyDataSetChanged();

    }

    public void DelFragment() {
        fragments.remove(fragments.size()-1);
        mAdapter.notifyDataSetChanged();
    }

    public static class MyAdapter extends FragmentStatePagerAdapter {

        private ArrayList<Fragment> fragments = null;
        private Context context;

        public MyAdapter(FragmentManager fm, ArrayList<Fragment> fragments) {
            super(fm);
            //this.context = context;
            this.fragments = fragments;
           // notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return fragments.size();//;NUM_ITEMS;
        }

        @Override
        public Fragment getItem(int position) {
            //return ArrayListFragment.newInstance(position);
            return fragments.get(position);
        }

        @Override
        public int getItemPosition(Object object) {
            // TODO Auto-generated method stub
            return PagerAdapter.POSITION_NONE;
        }
    }

//    public static class MyFragment extends Fragment {
//
//    }

    //Ctrl + /  : to do this
    public static class ArrayListFragment extends ListFragment {
        int mNum;

        /**
         * Create a new instance of CountingFragment, providing "num"
         * as an argument.
         */
        static ArrayListFragment newInstance(int num) {
            ArrayListFragment f = new ArrayListFragment();

            // Supply num input as an argument.
            Bundle args = new Bundle();
            args.putInt("num", num);
            f.setArguments(args);

            return f;
        }

        /**
         * When creating, retrieve this instance's number from its arguments.
         */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mNum = getArguments() != null ? getArguments().getInt("num") : 1;
        }

        /**
         * The Fragment's UI is just a simple text view showing its
         * instance number.
         */
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
            View tv = v.findViewById(R.id.text);
            ((TextView)tv).setText("Fragment #" + mNum);
            return v;
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            setListAdapter(new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_list_item_1, 0));
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            Log.i("FragmentList", "Item clicked: " + id);
        }
    }




}


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    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="0px"
        android:layout_weight="1">
    </android.support.v4.view.ViewPager>

    <LinearLayout android:orientation="horizontal"
        android:gravity="center" android:measureWithLargestChild="true"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0">
        <Button android:id="@+id/goto_first"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="add">
        </Button>
        <Button android:id="@+id/goto_last"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="del">
        </Button>
    </LinearLayout>
</LinearLayout>


fragment_pager_list.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:drawable/gallery_thumb">

    <TextView android:id="@+id/text"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:gravity="center_vertical|center_horizontal"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="hello_world"/>

    <!-- The frame layout is here since we will be showing either
    the empty view or the list view.  -->
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1" >
        <!-- Here is the list. Since we are using a ListActivity, we
             have to call it "@android:id/list" so ListActivity will
             find it -->
        <ListView android:id="@android:id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:drawSelectorOnTop="false"/>

        <!-- Here is the view to show if the list is emtpy -->
        <TextView android:id="@android:id/empty"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="No items."/>

    </FrameLayout>

</LinearLayout>

开发环境为Android Studio 2.2.3  最新版sdk 

compileSdkVersion 25
targetSdkVersion 25


源码下载

猜你喜欢

转载自blog.csdn.net/robert_cysy/article/details/71433638