AndroidでViewPagerを解決ページ数が3未満の場合、ページスライドブランクバグ


本demoでは以下の機能を実現
1、ページ数=1の場合、ページは静止する.
2、ページ数=>2の場合、ページスライドに空白は生じません
基本的な考え方
画像数が1の場合はスライドさせず、
画像数が2の場合は、元の画像順に順番に追加し、画像数を2倍にして4にし、空白ページの発生を防止しますが、マルチキャストポイントの個数は2と書いておけば、完璧に解決できます.
画像数がn>2の場合は、通常の書き方でよい.
package com.cloudhome.viewpagerproject;

import android.os.Bundle;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.android.volley.toolbox.NetworkImageView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    public InsuranceShop_ImageHandler InsuranceShop_handler = new InsuranceShop_ImageHandler(
            new WeakReference<MainActivity>(this));
    public ViewPager insurbanner;
    ArrayList<NetworkImageView> newImageViews;
    private NetworkImageView networkImageView;
    private ViewGroup group; //      Group
    private ImageView[] imageDots = null; //        
    private ImageView view;
    private ImageAdapter imageAdapter;
    private List<HeadImage> imageLists = new ArrayList<HeadImage>();
    private List<HeadImage> imageList_orginal = new ArrayList<HeadImage>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        initviewPage_img();
    }


    public void initviewPage_img() {


        HeadImage headImage_suoluetu1 = new HeadImage();
        HeadImage headImage_suoluetu2 = new HeadImage();
        HeadImage headImage_suoluetu3 = new HeadImage();
        HeadImage headImage_suoluetu4 = new HeadImage();
        HeadImage headImage_suoluetu5 = new HeadImage();


        headImage_suoluetu1
                .setIndexImgurl("http://i1.sinaimg.cn/gm/cr/2015/0413/1065544739.jpg");
        headImage_suoluetu2
                .setIndexImgurl("http://pic.58pic.com/58pic/12/81/24/81S58PICjnb.jpg");
        headImage_suoluetu3
                .setIndexImgurl("http://d.3987.com/qingx_150213/001.jpg");
        headImage_suoluetu4
                .setIndexImgurl("http://img3.imgtn.bdimg.com/it/u=2581234383,1952951452&fm=21&gp=0.jpg");
        headImage_suoluetu5
                .setIndexImgurl("http://image.baidu.com/search/detail?ct=503316480&z=1&tn=baiduimagedetail&ipn=d&word=%E9%A3%8E%E6%99%AF%20%E5%B0%8F%E5%B0%BA%E5%AF%B8&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=-1&cs=1808999674,2935367553&os=3410395349,124291932&simid=4178998595,794777276&pn=1&rn=1&di=123285481110&ln=1968&fr=&fmq=1460351344815_R&ic=0&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&is=&istype=2&ist=&jit=&bdtype=0&gsm=78&objurl=http%3A%2F%2Fimg.daimg.com%2Fuploads%2Fallimg%2F111111%2F3-11111116430K10.jpg");


        //         List    msg—handle    ,             

        // List<HeadImage> imageLists = (List<HeadImage>) msg.obj;


        //         1 n     
        imageList_orginal.add(headImage_suoluetu1);
        imageList_orginal.add(headImage_suoluetu2);
//        imageList_orginal.add(headImage_suoluetu3);
//        imageList_orginal.add(headImage_suoluetu4);
        //  imageLists.add(headImage_suoluetu5);


        initviewPage();


        newImageViews = new ArrayList<NetworkImageView>();


        switch (imageList_orginal.size()) {

            case 2:

                imageLists.add(imageList_orginal.get(0));
                imageLists.add(imageList_orginal.get(1));
                imageLists.add(imageList_orginal.get(0));
                imageLists.add(imageList_orginal.get(1));


                break;

            default:
                imageLists = imageList_orginal;

                break;

        }

        for (int i = 0; i < imageLists.size(); i++) {
            networkImageView = new NetworkImageView(
                    MainActivity.this);


            networkImageView.setScaleType(ImageView.ScaleType.FIT_XY);
            networkImageView.setDefaultImageResId(R.mipmap.white_bg);
            networkImageView.setImageUrl(imageLists.get(i)
                            .getIndexImgurl(),
                    VolleyTool.getInstance(MainActivity.this)
                            .getmImageLoader());

            newImageViews.add(networkImageView);

        }

        group.removeAllViews();
        imageDots = new ImageView[imageList_orginal.size()];//     
        for (int i = 0; i < imageDots.length; i++) {
            imageDots[i] = new ImageView(MainActivity.this);
            //     
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20);
            params.gravity = Gravity.CENTER_HORIZONTAL;
            params.setMargins(6, 0, 6, 0);
            imageDots[i].setLayoutParams(params);
            imageDots[i].setPadding(20, 0, 20, 0);
            if (i == 0) {
                imageDots[i]
                        .setBackgroundResource(R.mipmap.white_piont_icon);
            } else {
                imageDots[i]
                        .setBackgroundResource(R.mipmap.gray_piont_icon);
            }
            group.addView(imageDots[i]);
        }

        imageAdapter = new ImageAdapter(newImageViews);
        insurbanner.setAdapter(imageAdapter);
        imageAdapter.notifyDataSetChanged();
    }


    public void initviewPage() {

        insurbanner = (ViewPager) findViewById(R.id.insurbanner);
        group = (ViewGroup) findViewById(R.id.point_group);

        insurbanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            //   Adapter currentItem      。
            @Override
            public void onPageSelected(int arg0) {
                InsuranceShop_handler.sendMessage(Message.obtain(
                        InsuranceShop_handler,
                        InsuranceShop_ImageHandler.MSG_PAGE_CHANGED,
                        arg0, 0));

                int currentPosition = arg0 % imageList_orginal.size();
                for (int i = 0; i < imageList_orginal.size(); i++) {
                    imageDots[currentPosition]
                            .setBackgroundResource(R.mipmap.white_piont_icon);
                    if (currentPosition != i) {
                        imageDots[i]
                                .setBackgroundResource(R.mipmap.gray_piont_icon);
                    }
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            //                  
            @Override
            public void onPageScrollStateChanged(int arg0) {


                if (imageList_orginal.size() != 1 && imageList_orginal.size() > 1) {
                    switch (arg0) {


                        case ViewPager.SCROLL_STATE_DRAGGING:
                            InsuranceShop_handler
                                    .sendEmptyMessage(InsuranceShop_ImageHandler.MSG_KEEP_SILENT);

                            break;
                        case ViewPager.SCROLL_STATE_IDLE:
                            InsuranceShop_handler
                                    .sendEmptyMessageDelayed(
                                            InsuranceShop_ImageHandler.MSG_UPDATE_IMAGE,
                                            InsuranceShop_ImageHandler.MSG_DELAY);
                            break;


                        default:
                            break;
                    }
                }
            }
        });
        insurbanner.setCurrentItem(Integer.MAX_VALUE / 2);//      ,        
        //       
        InsuranceShop_handler.sendEmptyMessageDelayed(
                InsuranceShop_ImageHandler.MSG_BREAK_SILENT,
                InsuranceShop_ImageHandler.MSG_DELAY);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public class ImageAdapter extends PagerAdapter {

        private ArrayList<NetworkImageView> viewlist;

        public ImageAdapter(ArrayList<NetworkImageView> viewlist) {
            this.viewlist = viewlist;
        }

        @Override
        public int getCount() {
            //      ,        

            if (viewlist.size() == 1) {
                return 1;
            } else {
                return Integer.MAX_VALUE;
            }
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // Warning:       removeView

        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            //  ViewPager      View        
            position %= viewlist.size();

            if (position < 0) {
                position = viewlist.size() + position;
            }

            view = viewlist.get(position);

            //   View              ,    remove,     IllegalStateException。
            ViewParent vp = view.getParent();
            if (vp != null) {
                ViewGroup parent = (ViewGroup) vp;
                parent.removeView(view);
            }

            final String abc = imageLists.get(position).getIndexImgurl();

            // Log.d("position","1111111"+position+"");
            // Log.d("abc","1111111"+abc+"");
            view.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    for (int i = 0; i < imageLists.size(); i++) {
                        if (abc == imageLists.get(i).getIndexImgurl()) {

//                            bannerid = bannerlist.get(i).get("id").toString();
//                            banner_title = bannerlist.get(i).get("scene_name")
//                                    .toString();


                        }

                    }


                }
            });

            container.addView(view, 0);

            return view;
        }

    }
}

リソースのダウンロード