ViewPager轮播图 Handler方式实现

本文详细介绍了一种基于Android的轮播图实现方案,包括自定义BaseActivity基类简化页面开发,利用ViewPager进行图片轮播,通过BunnerAdapter适配器加载图片,以及使用NetUtils工具类进行网络请求。同时,文章还介绍了如何初始化图片加载框架,实现轮播图小圆点指示器的动态更新。
摘要由CSDN通过智能技术生成

1.提取的基类BaseActivity

package com.example.viewpager_demo;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

public abstract class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResId());
        //初始化视图
        initView();
        //加载数据
        initData();
    }
    protected abstract int getLayoutResId();
    //初始化视图
    protected abstract void initView();
    //加载数据
    protected abstract void initData();


}

2.MainActivity主页面

package com.example.viewpager_demo;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.Adaper.BunnerAdaper;
import com.example.Bean.BunnerBean;
import com.example.Util.NetUtils;

public class MainActivity extends BaseActivity {
    private String imageUrl = "https://api.tianapi.com/wxnew/?key=605fa0a929c8d8b116424df0510c6b2a&num=6&page=1";
    private ViewPager viewPager;
    private LinearLayout linearLayout;
    private TextView textView;
    private BunnerAdaper adaper;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    //初始化view
    @Override
    protected void initView() {
        viewPager = findViewById(R.id.v_pager);
        linearLayout = findViewById(R.id.L_layout);
        textView = findViewById(R.id.text);
        //创建适配器
        adaper = new BunnerAdaper(this);
        //设置给适配器
        viewPager.setAdapter(adaper);
        //滑动监听
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            //缓存的点
            private int index = -1;

            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                //改变textview
                textView.setText(adaper.getItem(i).getTitle());
                //改变当前点
                linearLayout.getChildAt(i % linearLayout.getChildCount()).setSelected(true);
                //还原原来的点
                if (index >= 0) {
                    linearLayout.getChildAt(index % linearLayout.getChildCount()).setSelected(false);
                }
                index = i;
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    //加载数据
    @Override
    protected void initData() {
        NetUtils.getInstance().getRequest(imageUrl, BunnerBean.class, new NetUtils.CallBack<BunnerBean>() {
            @Override
            public void onSuccess(BunnerBean o) {
                if (o == null || !o.isSuccess()) {
                    Toast.makeText(MainActivity.this, "请求错误", Toast.LENGTH_SHORT).show();
                    return;
                }
                adaper.setmList(o.getNewslist());
                //初始化小圆点的方法
                initDot(o.getNewslist().size());
                //切换到中间位置
                int center = adaper.getCount() / 2;
                center = center - center % o.getNewslist().size();
                viewPager.setCurrentItem(center);
                //开启轮播
                startLooper();
            }
        });
    }

    //创建handler
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
            handler.sendEmptyMessageDelayed(0, 2000);
        }
    };

    //开启轮播
    private void startLooper() {
        handler.removeCallbacksAndMessages(null);
        handler.sendEmptyMessageDelayed(0, 2000);
    }

    //初始化小圆点
    private void initDot(int size) {
        linearLayout.removeAllViews();
        for (int i = 0; i < size; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setBackgroundResource(R.drawable.select_dot);
            //布局参数 宽高包裹
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
            );
            int marage = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5,
                    getResources().getDisplayMetrics());
            params.leftMargin = marage;
            params.rightMargin = marage;
            linearLayout.addView(imageView, params);
        }
    }
}

3.适配器页面

package com.example.Adaper;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.Bean.BunnerBean;
import com.nostra13.universalimageloader.core.ImageLoader;

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

public class BunnerAdaper extends PagerAdapter {
    private List<BunnerBean.NewslistBean> mList;
    private Context mContext;

    public BunnerAdaper(Context mContext) {
        this.mContext = mContext;
        //出始化
        mList = new ArrayList<>();
    }
    public void setmList(List<BunnerBean.NewslistBean> lists){
        mList.clear();
        if(lists!=null){
            mList.addAll(lists);
        }
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return mList.size()>0?5000:0;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }
    public BunnerBean.NewslistBean getItem(int position){
        return mList.get(position%mList.size());
    }
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        ImageView imageView = new ImageView(mContext);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        container.addView(imageView);
        ImageLoader.getInstance().displayImage(getItem(position).getPicUrl(),imageView);
        return imageView;
    }

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

4.工具类

package com.example.Util;

import android.annotation.SuppressLint;
import android.os.AsyncTask;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class NetUtils {
    private static NetUtils instance;
    private Gson gson;
    public NetUtils() {
        gson = new Gson();
    }

    public static NetUtils getInstance() {
        if(instance == null){
            instance = new NetUtils();
        }
        return instance;
    }
    //执行一个网络请求返回string
    public String getRequest(String urlStr){
        String result = "";
        try {
            //定义url地址
            URL url = new URL(urlStr);
            //打开连接
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            //设置请求格式
            urlConnection.setRequestMethod("GET");
            //设置超时
            urlConnection.setReadTimeout(5000);
            urlConnection.setConnectTimeout(5000);
            //获取请求码
            int responseCode = urlConnection.getResponseCode();
            if(responseCode == 200){
                result = stream2String(urlConnection.getInputStream());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    //将字节流转换为字符流
    private String stream2String(InputStream inputStream) throws IOException {
        StringBuilder builder = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        for (String tmp = br.readLine();tmp!=null;tmp = br.readLine()){
            builder.append(tmp);
        }
        return builder.toString();
    }
    //执行一个网络请求返回bean
    public <E> E getRequest(String urlStr,Class clazz){
        return (E) gson.fromJson(getRequest(urlStr),clazz);
    }
    //定义接口
    public interface CallBack<E>{
        void onSuccess(E e);
    }
    //异步 回调请求
    @SuppressLint("StaticFieldLeak")
    public void getRequest(String urlStr, final Class clazz, final CallBack callBack){
        new AsyncTask<String,Void,Object>(){
            @Override
            protected Object doInBackground(String... strings) {
                return getRequest(strings[0],clazz);
            }

            @Override
            protected void onPostExecute(Object o) {
                callBack.onSuccess(o);
            }
        }.execute(urlStr);
    }
}

5.Bean类

package com.example.Bean;

import java.util.List;

public class BunnerBean {

    private int code;
    private String msg;
    private List<NewslistBean> newslist;
    private final int SUCCESS_CODE = 200;
    public boolean isSuccess(){
        return SUCCESS_CODE == code;
    }
    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<NewslistBean> getNewslist() {
        return newslist;
    }

    public void setNewslist(List<NewslistBean> newslist) {
        this.newslist = newslist;
    }

    public static class NewslistBean {
        private String ctime;
        private String title;
        private String description;
        private String picUrl;
        private String url;

        public String getCtime() {
            return ctime;
        }

        public void setCtime(String ctime) {
            this.ctime = ctime;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public void setPicUrl(String picUrl) {
            this.picUrl = picUrl;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }
}

6.Application初始化图片页面

package com.example.Application;

import android.app.Application;
import android.graphics.Bitmap;

import com.example.viewpager_demo.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class App extends Application {
    @Override
    public void onCreate() {

        ImageLoader.getInstance().init(new ImageLoaderConfiguration.Builder(this)
                .diskCacheSize(50*1024*1024)
                .memoryCacheSizePercentage(10)
                .defaultDisplayImageOptions(new DisplayImageOptions.Builder()
                        .cacheInMemory(true)
                        .cacheOnDisk(true)
                        .bitmapConfig(Bitmap.Config.RGB_565)
                        .showImageOnLoading(R.mipmap.ic_launcher)
                        .showImageForEmptyUri(R.mipmap.ic_launcher)
                        .showImageOnFail(R.mipmap.ic_launcher)
                        .build())
                .build());
        super.onCreate();
    }
}

7.布局页面

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <android.support.v4.view.ViewPager
        android:id="@+id/v_pager"
        android:layout_width="0dp"
        android:layout_height="200dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
    <LinearLayout
        android:id="@+id/L_layout"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:orientation="horizontal"
        app:layout_constraintRight_toRightOf="@id/v_pager"
        app:layout_constraintBottom_toBottomOf="@id/v_pager"
        android:padding="8dp"
        />
   <TextView
        android:id="@+id/text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:maxLines="1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/L_layout"
        app:layout_constraintBottom_toBottomOf="@id/v_pager"
        android:ellipsize="end"
        />
</android.support.constraint.ConstraintLayout>

7.轮播图小圆点

7.1默认圆点颜色
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    >
    <size
        android:width="8dp"
        android:height="8dp"
        />
    <solid
        android:color="#909090"
        />
</shape>

7.2选中圆点颜色
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    >
    <size
        android:width="8dp"
        android:height="8dp"
        />
    <solid
        android:color="#900000"
        />
</shape>

7.3select设置选中
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/shape_sel_dot" android:state_selected="true"></item>
    <item android:drawable="@drawable/shape_normal_dot" ></item>
</selector>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值