Android首页轮播图直接拿来用

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
 
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
 
public class HeadAD extends RelativeLayout {
    private ViewPager vp;
    private LinearLayout symbolLayout, bottomLayout;
    private LayoutParams lp;
    // private ArrayList<imageview> symbolViews;
    private List<viewpagerbean> showResults;
    private boolean isContinue = true;
    private int currentItem = 0; // 当前图片的索引号
 
    private ScheduledExecutorService updateService;
 
    private Context context;
 
    public void initData(List<viewpagerbean> pResult) {
        showResults = pResult;
    }
 
    public HeadAD(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        // setBackgroundResource(R.color.black);
 
    }
 
    public void initView(Context context) {
        // TODO Auto-generated method stub
 
        lp = new LayoutParams(LayoutParams.MATCH_PARENT, DensityUtil.dip2px(
                context, 180));
        vp = new ViewPager(context);
        vp.setLayoutParams(lp);
 
        lp = new LayoutParams(LayoutParams.MATCH_PARENT, DensityUtil.dip2px(
                context, 20));
 
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        bottomLayout = new LinearLayout(context);
        bottomLayout.setGravity(Gravity.CENTER);
        bottomLayout.setOrientation(LinearLayout.VERTICAL);
        bottomLayout.setLayoutParams(lp);
        bottomLayout.setBackgroundResource(R.color.footerBg);
 
        lp = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        symbolLayout = new LinearLayout(context);
        symbolLayout.setGravity(Gravity.CENTER);
        symbolLayout.setOrientation(LinearLayout.HORIZONTAL);
        symbolLayout.setPadding(0, 0, 5, 5);
 
        ImageView symbolIv;
        for (int i = 0; i < showResults.size(); i++) {
            if (showResults.size() > 1) {
                symbolIv = new ImageView(context);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
 
                params.rightMargin = 10;
                symbolIv.setBackgroundResource(R.drawable.point_bg);
                symbolIv.setEnabled(false);
                if (i == 0) {
                    symbolIv.setEnabled(true);
                } else {
                    symbolIv.setEnabled(false);
                }
                symbolIv.setLayoutParams(params);
                symbolLayout.addView(symbolIv);
            }
 
        }
        bottomLayout.addView(symbolLayout);
        adapter = new ViewPagerAdapter(context, showResults);
        vp.setAdapter(adapter);
        vp.setOnTouchListener(new OnTouchListener() {
 
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
 
                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isContinue = false;
                    break;
                case MotionEvent.ACTION_MOVE:
                    isContinue = false;
                    break;
                case MotionEvent.ACTION_UP:
                    isContinue = true;
                    break;
                case MotionEvent.ACTION_CANCEL:
                    break;
                }
                return false;
            }
        });
        vp.setOnPageChangeListener(new MyPageChangeListener());
        addView(vp);
        addView(bottomLayout);
 
    }
 
    private Handler viewPagerHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            vp.setCurrentItem(currentItem % showResults.size());// 切换当前显示的图片
        };
    };
    public ViewPagerAdapter adapter;
 
    // 直接在activity的OnResume里调用,当前界面是该activity时开始循环
 
    public void startUpdate() {
        this.updateService = Executors.newSingleThreadScheduledExecutor();
 
        this.updateService.scheduleAtFixedRate(new ScrollTask(), 5, 5,
                TimeUnit.SECONDS);
 
    }
 
    // 直接在activity的OnPause里调用,当前界面不是该activity时停止循环
 
    public void stopUpdate() {
        this.updateService.shutdown();
        updateService = null;
    }
 
    /**
     * 当ViewPager中页面的状态发生改变时调用
     *
     *
     */
    private class MyPageChangeListener implements OnPageChangeListener {
        private int oldPosition = 0;
 
        public void onPageSelected(int position) {
            currentItem = position % showResults.size();
            symbolLayout.getChildAt(oldPosition).setEnabled(false);
            symbolLayout.getChildAt(position).setEnabled(true);
            oldPosition = position;
        }
 
        public void onPageScrollStateChanged(int arg0) {
 
        }
 
        public void onPageScrolled(int arg0, float arg1, int arg2) {
 
        }
    }
 
    /**
     * 换行切换任务
     *
     * @author Administrator
     *
     */
    private class ScrollTask implements Runnable {
 
        public void run() {
            if (isContinue) {
                synchronized (vp) {
                    System.out.println("currentItem: " + currentItem);
                    currentItem = (currentItem + 1) % showResults.size();
                    viewPagerHandler.obtainMessage().sendToTarget(); // 通过Handler切换图片
                }
            }
        }
 
    }
 
}
</viewpagerbean></viewpagerbean></imageview>


HEADAD 实现了自定轮播计时。

 

下面看adapter写法 删除了部分项目逻辑

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.util.List;
 
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
 
 
import com.nostra13.universalimageloader.core.DisplayImageOptions;
 
/*******************************************************
 *
 *
 ********************************************************/
public class ViewPagerAdapter extends PagerAdapter {
 
    List<viewpagerbean> lists;
    Context ct;
    private ImageView imgView;
    private int currentPosition = 0;
    private DisplayImageOptions options;
 
    public ViewPagerAdapter(Context ct, List<viewpagerbean> mList) {
        lists = mList;
        this.ct = ct;
        options = new DisplayImageOptions.Builder().cacheInMemory(true)
                .cacheOnDisk(true)
                .showImageOnLoading(R.drawable.default_news_logo).build();
    }
 
    /**
     * 获得页面的总数
     */
    public int getCount() {
        return lists.size();
    }
 
    /**
     * 获得相应位置上的view container view的容器
     */
    public Object instantiateItem(ViewGroup container, final int position) {
        // imgView.setOnClickListener(this);
 
        imgView = new ImageView(ct);
 
        imgView.setScaleType(ImageView.ScaleType.FIT_XY);
        if (lists.size() == 0) {
 
        } else {
            //写自己的逻辑
            currentPosition = position % lists.size();
 
             
        }
         
 
        // 给 container 添加一个view
        container.addView(imgView);
        // 返回一个和该view相对的object
        return imgView;
    }
 
    /**
     * 判断 view和object的对应关系
     */
    public boolean isViewFromObject(View view, Object object) {
        if (view == object) {
            return true;
        } else {
            return false;
        }
    }
 
    /**
     * 销毁对应位置上的object
     */
    public void destroyItem(ViewGroup container, int position, Object object) {
 
        container.removeView((View) object);
        object = null;
    }
 
    @Override
    public int getItemPosition(Object object) {
        // TODO Auto-generated method stub
        return super.getItemPosition(object);
    }
 
}
</viewpagerbean></viewpagerbean>

实体bean这里就不贴了

 

用到工具类 ......还有几个不重要就不贴了

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import android.content.Context;
 
public class DensityUtil {
    /**
     * 根据手机的分辨率从 dip 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
 
    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
 
}

 

 

 

如何调用:

 

1
2
3
mViewPager = new HeadAD(getActivity(), null);
        mViewPager.initData(viewPagerLists);
        mViewPager.initView(getActivity());

就这样就OK了。

posted @ 2015-09-03 14:39  java高级技术汇  阅读(703)  评论(0编辑  收藏  举报