菜鸟的ViewPager使用

1.将ViewPager和Fragment绑定使用

(1) 继承FragmentPagerAdapter,重写ViewPager的适配器

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

/**
 * Created by qd on 2016/8/17.
 */
public class ViewPagerAdapter extends FragmentPagerAdapter {
    List<Fragment> fragmentList;

    public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
        super(fm);
        this.fragmentList = fragmentList;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

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

(2) 新建要添加的Fragment 以OneFragment为例子

public class ThreeFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_three, container, false);
        return view;
    }
}

(3) 添加数据,并为ViewPager添加适配器

public void initViewpager() {
        if(fragment1==null) fragment1 = new OneFragment();
        if(fragment2==null) fragment2=new TwoFragment();
        if(fragment3==null) fragment3=new ThreeFragment();
        if(fragment4==null) fragment4=new FourFragment();

        list.add(fragment1);
        list.add(fragment2);
        list.add(fragment3);
        list.add(fragment4);

        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), list);

        viewpager.setAdapter(viewPagerAdapter);
        //设置初始的时候显示第一页
        viewpager.setCurrentItem(0);

    }

(4)如果有指示器,则需要为ViewPager添加页面改变监听器

viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

2.使用ViewPager实现简单的轮播图效果(待优化)

(1) 准备图片素材:轮播时候需要显示的图片、指示器的选中和未选中状态时候的小圆点。
(2) 轮播图的布局

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

    <RelativeLayout
        android:id="@+id/rl_vp"
        android:layout_width="match_parent"
        android:layout_height="200dp">



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

        </android.support.v4.view.ViewPager>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_alignParentBottom="true"
            android:background="#88D0D0D0"
            android:padding="5dp"
            >
            <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="center">
                <ImageView
                    android:id="@+id/dot_0"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="5dp"
                    android:background="@mipmap/dot_normal"
                    />
                <ImageView
                    android:id="@+id/dot_1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="5dp"
                    android:background="@mipmap/dot_normal"
                    />
                <ImageView
                    android:id="@+id/dot_2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="5dp"
                    android:background="@mipmap/dot_normal"
                    />
                <ImageView
                    android:id="@+id/dot_3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="5dp"
                    android:background="@mipmap/dot_normal"
                    />
                <ImageView
                    android:id="@+id/dot_4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="5dp"
                    android:background="@mipmap/dot_normal"
                    />

            </LinearLayout>

        </LinearLayout>


    </RelativeLayout>

</RelativeLayout>

(3)代码实现 :最后一张切换至第一张的时候仍然存在BUG,等待修复

import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
    private int imageIds[];
    private String[] titles;
    private ArrayList<ImageView> images;
    private ArrayList<ImageView> dots;
    private TextView title;
    private ViewPager mViewPager;
    private ViewPagerAdapter adapter;
    private int oldPosition = 0;//记录上一次点的位置
    private int currentItem; //当前页面
    private ScheduledExecutorService scheduledExecutorService;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //图片ID
        imageIds = new int[]{
                R.mipmap.a,
                R.mipmap.b,
                R.mipmap.c,
                R.mipmap.d,
                R.mipmap.e
        };
        //图片标题
        titles = new String[]{
                "图片1",
                "图片2",
                "图片3",
                "图片4",
                "图片5"
        };
        //显示的图片
        images = new ArrayList<ImageView>();
        for(int i =0; i < imageIds.length; i++){
            ImageView imageView = new ImageView(this);
            imageView.setBackgroundResource(imageIds[i]);
            images.add(imageView);
        }
        //显示的点
        dots = new ArrayList<ImageView>();
        dots.add((ImageView)findViewById(R.id.dot_0));
        dots.add((ImageView)findViewById(R.id.dot_1));
        dots.add((ImageView)findViewById(R.id.dot_2));
        dots.add((ImageView)findViewById(R.id.dot_3));
        dots.add((ImageView)findViewById(R.id.dot_4));
        title = (TextView) findViewById(R.id.title);
        title.setText(titles[0]);
        mViewPager = (ViewPager) findViewById(R.id.vp);
        adapter = new ViewPagerAdapter();
        mViewPager.setAdapter(adapter);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                title.setText(titles[position]);
                dots.get(oldPosition).setBackgroundResource(R.mipmap.dot_normal);
                dots.get(position).setBackgroundResource(R.mipmap.dot_focused);
                oldPosition = position;
                currentItem = position;
            }
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }
            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }
    private class ViewPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return images.size();
            //return  Integer.MAX_VALUE;
        }
        //是否是同一张图片
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }
        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            view.removeView(images.get(position));
        }
        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            view.addView(images.get(position));
            return images.get(position);
        }
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        //每隔2秒钟切换一张图片
        scheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), 2, 2, TimeUnit.SECONDS);
    }

    //切换图片
    private class ViewPagerTask implements Runnable {
        @Override
        public void run() {
            currentItem = (currentItem +1) % imageIds.length;
            //更新界面
            handler.obtainMessage().sendToTarget();
        }
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            //设置当前页面
            mViewPager.setCurrentItem(currentItem);
        }
    };
}

(4) 运行效果

这里写图片描述

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/RainMcCom/article/details/52373274
个人分类: 菜鸟的Android
想对作者说点什么? 我来说一句

viewpager和fragment 搭配使用

2018年01月06日 35.17MB 下载

没有更多推荐了,返回首页

不良信息举报

菜鸟的ViewPager使用

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭