你的位置:首页 > 操作系统

[操作系统]自定义图片轮播,简单就是好用


图片轮播是一种常见的自定义控件,也有多种实现的方法,这里提供一种简单的ViewPager实现的案例。

实现功能:图片循环轮播,进度显示,图片点击事件

实现只需三步:

1 添加类文件到项目中。

2 在

3 实例化并设置简单参数。

具体使用方法,详见代码注释。

==================================================================

自定义java文件

package com.dashou.viewpagerimage;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* 自定义图片轮播控件
* 使用方法:
* 1 在 * 2 通过setViewPager()方法设置参数(int size, List<Map<String, Object>> list)
*   size是轮播图片的数量,list需要存入图片的url地址
* 3 设置此控件的监听事件
* 注意:Demo使用xutils请求网络
* Created by dashou on 2016/3/23.
*/
public class MyViewPager extends RelativeLayout implements View.OnTouchListener, ViewPager.OnPageChangeListener {

    private ViewPager viewPager;
    //放置圆点图片的布局
    private LinearLayout image;
    //设置图片填充方式
    public ImageView.ScaleType setScaleType = ImageView.ScaleType.FIT_XY;
    //存储图片url以及点击事件需要的id等数据
    private List<Map<String, Object>> list;
    private OnViewPagerClickListener onViewPagerClickListener;
    private int num;
    private int index_img = 0;
    public long time = 3000;//设置循环间隔时间
    private boolean isContinue = true;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            index_img++;
            viewPager.setCurrentItem(index_img);
        }
    };

    public MyViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    /**
     * 初始化控件
     */
    private void init() {
        viewPager = new ViewPager(getContext());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        addView(viewPager, lp);
        image = new LinearLayout(getContext());
        image.setOrientation(LinearLayout.HORIZONTAL);
        image.setGravity(Gravity.CENTER_VERTICAL);
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(200, 50);
        rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        rlp.addRule(RelativeLayout.CENTER_HORIZONTAL);
        addView(image, rlp);
    }

    /**
     * 设置ViewPager
     */
    public void setViewPager(int size, List<Map<String, Object>> list) {
        this.list = list;
        num = size;
        addDots(size);
        List<View> views = new ArrayList<View>();
        for (int i = 0; i < size; i++) {
            ImageView img = new ImageView(getContext());
            img.setScaleType(setScaleType);
            views.add(img);
        }
        MyViewPagerAdapter adapter = new MyViewPagerAdapter(getContext(), views);
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(this);
        viewPager.setOnTouchListener(this);
        startContinue();
    }

    /**
     * 添加进度显示
     *
     * @param size
     */
    private void addDots(int size) {
        for (int i = 0; i < size; i++) {
            LinearLayout.LayoutParams dot_lp=new LinearLayout.LayoutParams(5,30);
            dot_lp.width=0;
            dot_lp.weight = 1.0f;
            TextView tv = new TextView(getContext());
            if (i==0){
                tv.setText(i+1+"");
                tv.setTextColor(Color.RED);
            }else {
                tv.setText(i+1+"");
                tv.setTextColor(Color.BLUE);
            }
            image.addView(tv,dot_lp);
        }
    }

    //重置图片状态按钮
    private void resetDots(int id){
        for (int i = 0; i < list.size(); i++) {
            ((TextView)(image.getChildAt(i))).setTextColor(Color.BLUE);
        }
        ((TextView)(image.getChildAt(id))).setTextColor(Color.RED);
    }
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                isContinue = false;
                break;
            case MotionEvent.ACTION_UP:
                isContinue = true;
                break;
            default:
                isContinue = true;
                break;
        }
        return false;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        index_img = position;
        resetDots(position%list.size());
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    //图片点击事件对外接口
    interface OnViewPagerClickListener {
        /**
         * 图片点击事件监听
         * @param position 对应被点击的图片
         */
        void OnViewPager(int position);
    }
    //初始化接口方法
    public void setOnViewPagerClickListener(OnViewPagerClickListener onViewPagerClickListener) {
        this.onViewPagerClickListener = onViewPagerClickListener;
    }

    //启动线程循环播放图片
    private void startContinue() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                while (viewPager!=null) {
                    try {
                        sleep(time);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (isContinue){
                        Message msg = Message.obtain();
                        msg.what = 0;
                        handler.sendMessage(msg);
                    }
                }
            }
        }.start();
    }

    /**
     * ViewPager适配器
     */
    class MyViewPagerAdapter extends PagerAdapter {
        private final List<View> views;
        private ImageOptions imageOptions = new ImageOptions.Builder()
                .build();

        public MyViewPagerAdapter(Context context, List<View> views) {
            this.views = views;
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            final int mposition = position%views.size();
            View view = views.get(mposition);
            ViewPager viewPager = (ViewPager) container;
            if (view instanceof ImageView) {
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //调用MyViewPager里的接口
                        if (onViewPagerClickListener!=null){
                            onViewPagerClickListener.OnViewPager(mposition);
                        }
                    }
                });
            }
            //使用加载图片
            x.image().bind((ImageView) view, list.get(mposition).get("url").toString(), imageOptions);
            viewPager.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
        }
    }
}

===============================================================

<?<RelativeLayout     android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.dashou.viewpagerimage.MyViewPager
        android:id="@+id/myViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </com.dashou.viewpagerimage.MyViewPager>
</RelativeLayout>

====================================================================

Activity代码

package com.dashou.viewpagerimage;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ContentView(R.layout.activity_main)
public class MainActivity extends Activity implements MyViewPager.OnViewPagerClickListener {

    //实例化控件********注意此Demo使用xutils请求
    @ViewInject(R.id.myViewPager)
    private MyViewPager myViewPager;
    private String[] img_url = {"http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/6697838.jpg",
            "http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/1439024.jpg",
            "http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/1439025.jpg",
            "http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/1439021.jpg",
            "http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/1439020.jpg",
            "http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/1439022.jpg",
            "http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/1439023.jpg"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setMyViewPager();
    }

    private void setMyViewPager() {
        //准备list资源
        List<Map<String, Object>> views_list = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < img_url.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("url", img_url[i]);
            views_list.add(map);
        }
        //需要两个参数 1. 数量 2.url地址list
        myViewPager.setViewPager(img_url.length, views_list);
        myViewPager.setOnViewPagerClickListener(this);
    }

    @Override
    public void OnViewPager(int position) {
        //这里实现图片点击后的操作
        int id = position+1;
        Toast.makeText(this,"第"+id+"张图片被点击了",Toast.LENGTH_SHORT).show();
    }
}

======================================================

结束