1. 程式人生 > >Banner輪播圖

Banner輪播圖

1.佈局

 <com.youth.banner.Banner
        android:id="@+id/banner"
        android:layout_width="match_parent"
        android:layout_height="300dp">

    </com.youth.banner.Banner>

2.MainActivity

package fragm;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.yuan.zonghe.NetUtil.NetUtils;
import com.example.yuan.zonghe.R;

import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoaderInterface;

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

import bean.ImageBean;

public class MyFragment extends Fragment {
    private String str="https://api.tianapi.com/wxnew/?key=605fa0a929c8d8b116424df0510c6b2a&num=6&page=1";
    private Banner banner;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.myfragment,container,false);
        //獲取控制元件
        banner = view.findViewById(R.id.banner);
//設定banner樣式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
        //設定圖片載入器
        banner.setImageLoader(new ImageLoaderInterface<ImageView>() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                ImageBean.NewslistBean bean= (ImageBean.NewslistBean) path;
                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(bean.getPicUrl(),imageView);


            }

            @Override
            public ImageView createImageView(Context context) {
                ImageView imageView=new ImageView(context);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                return imageView;
            }

        });

        initData();
        return view;
    }

    private void initData() {

       NetUtils.getInstance().getRequest(str, ImageBean.class, new NetUtils.CallBack<ImageBean>() {
           @Override
           public void onSuccess(ImageBean o) {
                banner.setImages(o.getNewslist());
                banner.setBannerTitles(getTitles(o));
                banner.start();
           }
       });

    }
    private List<String> getTitles(ImageBean ima)
    {
        List<String> list=new ArrayList<>();
        for (ImageBean.NewslistBean banner:ima.getNewslist())
        {
            list.add(banner.getTitle());
        }
        return list;
    }
}

3.工具類  NetUtils

package com.example.yuan.zonghe.NetUtil;

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);
    }


}

4.Adapter

package adapter;

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.nostra13.universalimageloader.core.ImageLoader;

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

import bean.ImageBean;

public class ImageAdapter extends PagerAdapter {

    private Context mContext;
    private List<ImageBean.NewslistBean> mDatas;

    public ImageAdapter(Context mContext) {
        this.mContext = mContext;
        mDatas=new ArrayList<>();
    }


    @Override
    public int getCount() {
        return mDatas.size()>0 ? 5000 : 0;
    }

    public void setmDatas(List<ImageBean.NewslistBean> datas) {
        mDatas.clear();
        if (datas!=null)
        {
            mDatas.addAll(datas);
        }
        notifyDataSetChanged();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view==o;
    }
    public ImageBean.NewslistBean getItem(int position) {
        return mDatas.get(position % mDatas.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);
    }
}

5.初始化

package com.example.yuan.zonghe.NetUtil;

import android.app.Application;

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() {
        super.onCreate();
        ImageLoaderConfiguration configuration=null;
        configuration=new ImageLoaderConfiguration.Builder(this)
                .memoryCacheSizePercentage(10)
                .discCacheSize(50 * 1024 * 1024)
                .defaultDisplayImageOptions(
                        new DisplayImageOptions.Builder()

                                .cacheInMemory(true)
                                .cacheOnDisk(true)
                                .build()
                )
                .build();
        ImageLoader.getInstance().init(configuration);
    }
}

6.許可權   以及初始化 App

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

7.依賴,

design, image-loader   

banner  依賴    

implementation 'com.youth.banner:banner:1.4.10'