轮播图在每个app中扮演着一个点缀的角色,在独立做了三款app后都有这个需求,所以我决定把它单独抽出来。以后只需copy,然后再根据需求改一下即可。
/**
* 加载网络轮播图
*@author jiangrongtao
*
*csdn:http://blog.csdn.net/jiang_rong_tao
*
*github:https://github.com/jiangrongtao/jiangrongtao.github.io
*
* created at 2016/6/3 9:14
*/
public class BannerView {
private View bannerView;
private Context mContext;
private Map<String,String> maps;
private FragmentManager manager;
private List<Fragment> mList;
private MyChildViewPager bannerPager;
private ImageView defImage;//设置默认图片
public static boolean LOAD_FINISH=false;//是成功加载banner
private LinearLayout llDots;//下部的小白点的布局
public boolean isRoll = false;//是否轮播
private List<View> dotList = new ArrayList<View>();//存放小白点
private static final String TAG = "BannerView";
public BannerView(Context context,Map<String,String> maps,FragmentManager manager){
this.mContext=context;
this.maps=maps;
this.manager=manager;
mList=new ArrayList<Fragment>();
}
protected Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
final List<BannerInfo> data = (List<BannerInfo>) msg.obj;
setBannerInfo(data);
break;
case 2:
LOAD_FINISH=false;
defImage.setVisibility(View.VISIBLE);
break;
case 3:
if (mList.size() > 0) {
bannerPager.setCurrentItem((bannerPager.getCurrentItem() + 1) % mList.size());
} else {
isRoll = false;
}
break;
}
}
};
/**
* 设置banner信息
* @param data
*/
private void setBannerInfo(final List<BannerInfo> data) {
mList.clear();
for (int i = 0; i < data.size(); i++) {
final int j = i;
final ImageView imageView = new ImageView(mContext);
BannerInfo bannerInfo = data.get(i);
APIImageLoader.displayImage(mContext,bannerInfo.getUrl(), R.drawable.banner_fial,R.drawable.banner_fial,imageView);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String hrefUrl = data.get(j).getHrefUrl();
if (!TextUtils.isEmpty(hrefUrl)) {
Intent intent = new Intent(mContext, AppDetailActivity.class);
intent.putExtra("hrefUrl", hrefUrl);
mContext.startActivity(intent);
}
}
});
Fragment fragment = new Fragment() {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return imageView;
}
};
mList.add(fragment);
}
if(mList.size()>0){
defImage.setVisibility(View.GONE);
bannerPager.setAdapter(new BannerAdapter(manager, mList));
initDot();
bannerPager.setCurrentItem(0);
LOAD_FINISH=true;
}else{
LOAD_FINISH=false;
defImage.setVisibility(View.VISIBLE);
}
}
public View getBannerView() {
bannerView=View.inflate(mContext, R.layout.banner_layout,null);
bannerPager= (MyChildViewPager) bannerView.findViewById(R.id.banner_pager);
defImage = (ImageView)bannerView.findViewById(R.id.iv_default_page);
llDots=(LinearLayout)bannerView.findViewById(R.id.ll_dots);
initBannersData();
return bannerView;
}
/*
* 设置循环轮播
* */
public void setBannerCycle(long loopTime){
if(LOAD_FINISH){
if(null!=bannerPager){
isRoll=true;
startLooper(loopTime);
bannerPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
switchDot(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
}
/**
* 开启轮播
* @param loopTime 轮播间隔时间
*/
private void startLooper(final long loopTime) {
new Thread() {
public void run() {
while (isRoll) {
handler.sendEmptyMessageDelayed(3,loopTime);
}
};
}.start();
}
//获取网络banner图片
private void initBannersData() {
maps.clear();
RequestManager.getInstance(mContext).sendPost(APIConfig.GET_BANNERS, maps, BannerRes.class, new Callback<BannerRes>() {
@Override
public BannerRes parseNetworkResponse(Response response) throws Exception {
return GsonUtils.object(response.body().string(),BannerRes.class);
}
@Override
public void onError(Call call, Exception e) {
}
@Override
public void onResponse(BannerRes response) {
if(APIResCode.SUCCESS.equals(response.getResCode())){
List<BannerInfo> data = response.getData();
if (data!=null&&data.size()>0){
handler.sendMessage(handler.obtainMessage(1, data));
}else{
handler.sendEmptyMessage(2);
}
}
}
});
}
/**
* 初始化小圆点
*/
private void initDot() {
llDots.removeAllViews();
dotList.clear();
for (int i = 0; i < mList.size(); i++) {
View view = new View(mContext);
//默认选中第一个小白点
view.setBackgroundResource(i == 0?R.drawable.dot_sel:R.drawable.dot_nor);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(8, 8);
params.setMargins(0, 0, 12, 0);
llDots.addView(view, params);
dotList.add(view);
}
}
/**
* 切换圆点
*/
private void switchDot(int position) {
for (int i = 0; i < dotList.size(); i++) {
dotList.get(i).setBackgroundResource(i == position?R.drawable.dot_sel:R.drawable.dot_nor);
}
}
}
轮播图适配器:
public class BannerAdapter extends FragmentPagerAdapter{
List<Fragment> list ;
public BannerAdapter(FragmentManager fm, List<Fragment> list) {
super(fm);
this.list = list ;
}
@Override
public Fragment getItem(int index) {
return list.get(index%list.size());
}
@Override
public int getCount() {
return list.size();
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<com.jianzhilaila.money.ui.view.myviewpager.MyChildViewPager
android:id="@+id/banner_pager"
android:layout_width="match_parent"
android:layout_height="200dp">
</com.jianzhilaila.money.ui.view.myviewpager.MyChildViewPager>
<ImageView
android:id="@+id/iv_default_page"
android:layout_width="match_parent"
android:layout_height="208dp"
android:background="@drawable/banner_fial" />
<LinearLayout
android:id="@+id/ll_dots"
android:layout_width="match_parent"
android:layout_height="8dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:layout_gravity="bottom"
android:layout_marginBottom="10dp"
android:orientation="horizontal" />
</FrameLayout>
具体用法
//获取banner
BannerView bannerView = new BannerView(context, maps, getChildFragmentManager());
View banner = bannerView.getBannerView();
mLinearLayout.addView(banner,0);
bannerView.setBannerCycle(1500);
在onDestroyView()或onDestroy()中记得设置:**isRoll=false;** ,避免内存溢出。
mLinearLayout是轮播图页面的根布局。getChildFragmentManager是由于我的Viewpager是嵌套使用的。MyChildViewPager 是一个自定义的防止嵌套使用滑动事件冲突的类。RequestManager和APIImageLoader是我自己二次封装的网络请求和图片加载类,在我以前的博客http://blog.csdn.net/jiang_rong_tao/article/details/51516977中。
注意:上面代码有很多要改进的地方,如果有bug自己修复,可以把改进的代码分享一下。