ViewPager详解

一、ViewPager使用

(1)ViewPager常用方法

  • setAdapter():设置适配器
  • setCurrentItem():跳转到特定的页面
  • setOffscreenPageLimit():设置缓存的页面个数,默认是 1
  • addOnPageChangeListener():设置页面滑动时的监听器
  • setPageTransformer():设置页面切换时的动画效果
  • setPageMargin():设置不同页面之间的间隔
  • setPageMarginDrawable():设置不同页面间隔之间的装饰图,需要同时设置setPageMargin()
  • getPageTitle():设置标题名称
  • getCurrentItem():返回当前显示的页码

(2)PagerAdapter类

public class MyPagerAdapter extends PagerAdapter {
    private Context context;
    private List list;

    public MyPagerAdapter(Context context, List list) {
        this.context = context;
        this.list = list;
    }

    //显示多少个页面
    @Override
    public int getCount() {
        if (list != null && list.size() > 0) {
            return list.size();
        } else {
            return 0;
        }
    }

    //判断初始化返回的Object是不是一个View对象
    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    //初始化显示的条目对象
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        ImageView imageView = new ImageView(context);
        imageView.setImageDrawable(context.getResources().getDrawable(list.get(position)));
        container.addView(imageView);
        return imageView;
    }

    //销毁条目对象
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }
}
  • 在代码中调用
ViewPager view_pager = findViewById(R.id.view_pager);
List list = new ArrayList<>();
list.add(R.drawable.ic_launcher);
list.add(R.drawable.ic_launcher);
list.add(R.drawable.ic_launcher);
list.add(R.drawable.ic_launcher);
MyPagerAdapter adapter = new MyPagerAdapter(this, list);
view_pager.setAdapter(adapter);

adapter.notifyDataSetChanged()//刷新界面

(3)FragmentPagerAdapter与FragmentStatePagerAdapter实现

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

    private List list = new ArrayList<>();

    @SuppressLint("WrongConstant")
    public MyFragmentPagerAdapter(@NonNull FragmentManager fm) {
        super(fm, 0);
        list.add(new PagerFragment());
        list.add(new PagerFragment());
        list.add(new PagerFragment());
        list.add(new PagerFragment());
    }

    //显示的fragment对象
    @NonNull
    @Override
    public Fragment getItem(int position) {
        return list.get(position);
    }

    //ViewPager页面的数量
    @Override
    public int getCount() {
        return list.size();
    }
}
  • 在代码中实现调用
MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
view_pager.setAdapter(myFragmentPagerAdapter);
  • FragmentPagerAdapter对于不再需要的fragment,FragmentPagerAdapter则选择调用事务的detach() 方法,而非remove()方法来处理它。
  • FragmentPagerAdapter只是销毁了fragment的视图,但仍将fragment实例保留在FragmentManager中。因此, FragmentPagerAdapter创建的fragment永远不会被销毁。
  • 使用FragmentStatePagerAdapter会销毁掉不需要的fragment。事务提交后,可将fragment从activity的FragmentManager中彻底移除。

(4)ViewPager + TableLayout使用

public class MyPagerAdapter extends PagerAdapter {
    private Context context;
    private List list;
    private String[] titles = new String[]{"标题一", "标题二", "标题三", "标题四"};

    public MyPagerAdapter(Context context, List list) {
        this.context = context;
        this.list = list;
    }

    //显示多少个页面
    @Override
    public int getCount() {
        if (list != null && list.size() > 0) {
            return list.size();
        } else {
            return 0;
        }
    }

    //判断初始化返回的Object是不是一个View对象
    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    //初始化显示的条目对象
    @SuppressLint("SetTextI18n")
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        ImageView imageView = new ImageView(context);
        imageView.setImageDrawable(context.getResources().getDrawable(list.get(position)));
        container.addView(imageView);
        return imageView;
    }

    //销毁条目对象
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    //触发销毁和重建
    @Override
    public int getItemPosition(@NonNull Object object) {
        return POSITION_NONE;
    }

    //设置标题
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }
}
  • 代码中调用
ViewPager view_pager = findViewById(R.id.view_pager);
tableLayout.setupWithViewPager(view_pager);
tableLayout.setTabMode(TabLayout.MODE_SCROLLABLE);//设置摆动方式

二、ViewPager实现首页轮播图效果

(1)在MyPagerAdapter实现显示banner图片、标题、点击事件

public class MyPagerAdapter extends PagerAdapter {
    private Context context;
    private List list;
    private String[] titles = new String[]{"标题一", "标题二", "标题三", "标题四"};

    public MyPagerAdapter(Context context, List list) {
        this.context = context;
        this.list = list;
    }

    //显示多少个页面
    @Override
    public int getCount() {
        if (list != null && list.size() > 0) {
            return list.size();
        } else {
            return 0;
        }
    }

    //判断初始化返回的Object是不是一个View对象
    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    //初始化显示的条目对象
    @SuppressLint("SetTextI18n")
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_pager, container, false);
        ImageView imageView = view.findViewById(R.id.banner_image);
        TextView textView = view.findViewById(R.id.banner_title);
        imageView.setImageDrawable(context.getResources().getDrawable(list.get(position)));
        textView.setText("轮播图标题内容------" + position);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bannerClickListener.onBannerClick(v, position);
            }
        });
        container.addView(view);
        return view;
    }

    //销毁条目对象
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    //触发销毁和重建
    @Override
    public int getItemPosition(@NonNull Object object) {
        return POSITION_NONE;
    }

    //设置标题
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }

    private BannerClickListener bannerClickListener;

    public interface BannerClickListener {
        void onBannerClick(View view, int position);
    }

    //通过实现接口处理点击事件
    public void setBannerClickListener(BannerClickListener bannerClickListener) {
        this.bannerClickListener = bannerClickListener;
    }
}

(2)在Activity中代码实现

public class MainActivity extends AppCompatActivity {

    private TabLayout tableLayout;
    private ViewPager view_pager;
    private LinearLayout linearLayout;
    private List list;
    private List roundList;
    private MyPagerAdapter adapter;

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

        //适配adapter
        view_pager.setAdapter(adapter);
        //设置标题
        tableLayout.setupWithViewPager(view_pager);
        //设置摆动方式
        tableLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        //设置滑动监听
        view_pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            //当前页面发生滑动时调用
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            //页面滑动结束,选定页面时调用
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < roundList.size(); i++) {
                    if (position % roundList.size() == i) {
                        roundList.get(i).setImageResource(R.drawable.ic_launcher);
                    } else {
                        roundList.get(i).setImageResource(R.drawable.ic_launcher_s);
                    }
                }
            }

            //当滑动状态改变时调用
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //设置轮播图点击事件监听
        adapter.setBannerClickListener(new MyPagerAdapter.BannerClickListener() {
            @Override
            public void onBannerClick(View view, int position) {

            }
        });
    }

    private void initView() {
        tableLayout = findViewById(R.id.table_layout);
        view_pager = findViewById(R.id.view_pager);
        linearLayout = findViewById(R.id.linearLayout);
    }

    private void initData() {
        //添加轮播图图片
        list = new ArrayList<>();
        list.add(R.mipmap.ic_launcher);
        list.add(R.mipmap.ic_launcher);
        list.add(R.mipmap.ic_launcher);
        list.add(R.mipmap.ic_launcher);
        adapter = new MyPagerAdapter(this, list);

        //添加轮播图圆点
        roundList = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            ImageView imageView = new ImageView(this);
            if (i == 0) {
                imageView.setImageResource(R.drawable.ic_launcher);
            } else {
                imageView.setImageResource(R.drawable.ic_launcher_s);
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(16, 16);
            params.setMargins(5, 0, 5, 0);
            linearLayout.addView(imageView, params);
            roundList.add(imageView);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

你可能感兴趣的:(ViewPager详解)