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

Banner輪播圖!

1.佈局

依賴 

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

<?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">

   <com.youth.banner.Banner
       android:id="@+id/banner1"
       android:layout_width="match_parent"
       android:layout_height="200dp"></com.youth.banner.Banner>
</android.support.constraint.ConstraintLayout>

2.主頁面

package com.bw.ymy.lunbo;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoaderInterface;

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

public class MainActivity extends AppCompatActivity {
    private Banner banner1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //獲取資源id
        banner1=findViewById(R.id.banner1);
        //設定文字
        banner1.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);

        banner1.setImageLoader(new ImageLoaderInterface<ImageView>() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                Bean.NewslistBean bean= (Bean.NewslistBean) path;
                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;
            }
        });
        indata();
    }
    private  void  indata()
    {
        Netiul.getInstance().getRequest("https://api.tianapi.com/wxnew/?key=c4aa776e0a51d57d6750511e2baa46b6&num=6&page=1",
                Bean.class,new Netiul.Callback<Bean>()
                {
                    @Override
                    public void onsuccess(Bean bean) {
                        banner1.setImages(bean.getNewslist());
                        banner1.setBannerTitles(getTitles(bean));
                        banner1.start();
                    }
                });
    }
    private List<String> getTitles(Bean bannerResponse) {
        List<String> list = new ArrayList<>();
        for (Bean.NewslistBean banner: bannerResponse.getNewslist()) {
            list.add(banner.getTitle());
        }
        return list;
    }


}

3.工具類

package com.bw.ymy.lunbo;

import android.os.AsyncTask;
import android.provider.CallLog;

import com.google.gson.Gson;
import com.youth.banner.Banner;

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 Netiul {
    public  static  Netiul instance;

    public Netiul() {
    }
    public  static  Netiul getInstance()
    {
        if(instance==null)
        {
            instance=new Netiul();
        }
        return  instance;
    }
    public  interface  Callback<T>{
        void  onsuccess(T t);

    }
    public  void getRequest(final 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);
    }
    public  <T> T getRequest(String urlStr,Class clazz)
    {
        return (T) new Gson().fromJson(getRequest(urlStr),clazz);
    }
    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();
    }

}

4.App

package com.bw.ymy.lunbo;

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();
        ImageLoader.getInstance().init(
                new ImageLoaderConfiguration.Builder(this)
                        .memoryCacheSizePercentage(10)
                        .discCacheSize(50 * 1024 * 1024)
                        .defaultDisplayImageOptions(
                                new DisplayImageOptions.Builder()
                                        .showImageOnFail(R.mipmap.ic_launcher)
                                        .showImageOnLoading(R.mipmap.ic_launcher)
                                        .cacheInMemory(true)
                                        .cacheOnDisk(true)
                                        .build()
                        )
                        .build()
        );
    }
}



5.Bean類

package com.bw.ymy.lunbo;

import java.util.List;

public class Bean {

    /**
     * code : 200
     * msg : success
     * newslist : [{"ctime":"2018-11-18","title":"普通人的汽車基礎知識到底有多差?","description":"易車","picUrl":"http://mmbiz.qpic.cn/mmbiz_jpg/tXmTSicVPQ6enLlOibt3RlJsElhn3s1HU26m15CuHDMvWKU0g4xCEadHksFVdzkdibHVRUQlibBsttpMicE64ib8LCTw/0?wx_fmt=jpeg","url":"https://mp.weixin.qq.com/s?src=11&timestamp=1542540609&ver=1252&signature=eMbdrP2jsY3rO29rXPW0Mz3YTbYZIwL8JT9LjdhLdvUaZ3CSWe*NqMvBtI3P9jItt6urlZ*HbhICMVsBzZcZzBaNDj7ovAaBcoDv7bvk*BuVfBfQElBent5ZfHSnUiJk&new=1"},{"ctime":"2018-11-18","title":"韋德可能沒法大帽詹姆斯了。詹姆斯輸球了還要被為難。","description":"詹姆斯說","picUrl":"http://mmbiz.qpic.cn/mmbiz_jpg/geLkPvpOhUSO2UZDgmdp9iaHwC8syFWAPnS6wf5Xq8HRY3TVjbhMZQJTdYyLiaBLNB8kg1Q99ZMLicokH702Yclyg/0?wx_fmt=jpeg","url":"https://mp.weixin.qq.com/s?src=11&timestamp=1542540620&ver=1252&signature=*Jkik6mGD1Zjx20taBuMMyI01LxdBjrST1Hl9qhvOWpbDZCpUbM*a4SxO4cFUWEgZp*TY6ASE2jRvdjWqCP7WiowIDj0LPxLZxF4A6rErNu4YIbRkoaIufCbUHs*D8GJ&new=1"},{"ctime":"2018-11-18","title":"賽季首個60分誕生!喬老闆還捨得交易他嗎?","description":"騰訊NBA","picUrl":"http://mmbiz.qpic.cn/mmbiz_jpg/OQeAz51Lq7JibYuSOIN7rzSr9BqczGSCSnx4oUoEZgGPTlgNOBuIJyObDOiaTwaAKebqzlRtfXJ9uyM6E7er85Cw/0?wx_fmt=jpeg","url":"https://mp.weixin.qq.com/s?src=11&timestamp=1542540620&ver=1252&signature=Ww97b063b9rf0C2OQhdWhCCr74SFNozO6bNuXNeWWl1is6XAzr6KnhtaKBHWDua50*jAbV51OY9MneKP9sAS2Z*tctHx4tGPbposKhE6SMP0vWe5XvzUH5zAat0a5coQ&new=1"},{"ctime":"2018-11-18","title":"中國移動:5G時代每月人均流量至少60GB","description":"電腦報","picUrl":"http://mmbiz.qpic.cn/mmbiz_jpg/HrhrgxCloNaicMKjagZsNzVnsVCkAhwFSPyJQu8l5w71cfgwfKaHArMWCna3zYAdLAnRd6NBKbg2icdfmSWyZiaWQ/0?wx_fmt=jpeg","url":"https://mp.weixin.qq.com/s?src=11&timestamp=1542540606&ver=1252&signature=HGPVWHZAaOPdxUZbFx4o79dHIwvT4DniBaLk1Li-b0pkbywkWwZqurbDiFEerjX*wz1T8nbiTRvYhAIyyNIij8UU2i6gtZA2M0Wb9GihMIcwpu4BG6od-Ccjlld1OXiP&new=1"},{"ctime":"2018-11-18","title":"周小川國內首談數字貨幣和電子支付:有三方面扭曲 有些技術只關注如何圈錢","description":"大公網","picUrl":"http://mmbiz.qpic.cn/mmbiz_jpg/1rNDCX3Xn4E6s6jCJFjYibdIrQ6ESE8leib5ZVsSSyqViaOZ4ImaGPnrCVKH49libAibx6LsyXWGcsZ205jxNjqckEA/0?wx_fmt=jpeg","url":"https://mp.weixin.qq.com/s?src=11&timestamp=1542540608&ver=1252&signature=oS4sTMvXomHQzgHGXjNZGyT6ljjuYwuyhaBkrr5deynbaymihpsyi1AGREauBNbNvHH76cbYdxvXr7zbfz2y3NxNphFXx5cDUIjj7m2VwT82wIVe4EdE9oP6F45wLulJ&new=1"},{"ctime":"2018-11-18","title":"湖北:半歲嬰兒\u201c灌腸\u201d退燒 退燒不成反腎衰 面臨終身透析","description":"醫群網","picUrl":"http://mmbiz.qpic.cn/mmbiz_jpg/AuyMO4zftIqRF8NicTCuTicYFpbD72XyEq8UA2IGgxYDocezyoQwxfDMor8YopxeAtsoXbcILVWh6UhoZGDAZuNQ/0?wx_fmt=jpeg","url":"https://mp.weixin.qq.com/s?src=11&timestamp=1542540603&ver=1252&signature=ETBgeBQQNDkh6GalturYW4UDspDW2xTh8imKCtSPk46bUs2vzDZfzFdhdNyOknc-RvtCTQa8VQ*kE8Yj0v23WVeWE26Yf-G53F*GYgoY3321H7jqg3lPpL1IVTLzArYb&new=1"}]
     */

    private int code;
    private String msg;
    private List<NewslistBean> newslist;

    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 {
        /**
         * ctime : 2018-11-18
         * title : 普通人的汽車基礎知識到底有多差?
         * description : 易車
         * picUrl : http://mmbiz.qpic.cn/mmbiz_jpg/tXmTSicVPQ6enLlOibt3RlJsElhn3s1HU26m15CuHDMvWKU0g4xCEadHksFVdzkdibHVRUQlibBsttpMicE64ib8LCTw/0?wx_fmt=jpeg
         * url : https://mp.weixin.qq.com/s?src=11&timestamp=1542540609&ver=1252&signature=eMbdrP2jsY3rO29rXPW0Mz3YTbYZIwL8JT9LjdhLdvUaZ3CSWe*NqMvBtI3P9jItt6urlZ*HbhICMVsBzZcZzBaNDj7ovAaBcoDv7bvk*BuVfBfQElBent5ZfHSnUiJk&new=1
         */

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

補充 :無關緊要

package com.bw.ymy.zonghe2.Nutil;

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

import com.bw.ymy.zonghe2.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() {
        super.onCreate();
        ImageLoader.getInstance().init(new ImageLoaderConfiguration.Builder(this)
                .diskCacheSize(50*1024*1024)
                .memoryCacheSizePercentage(10)
                .defaultDisplayImageOptions(new DisplayImageOptions.Builder()
                        .bitmapConfig(Bitmap.Config.RGB_565)
                        .cacheInMemory(true)
                        .cacheOnDisk(true)
                        .showImageOnFail(R.mipmap.ic_launcher)
                        .showImageForEmptyUri(R.mipmap.ic_launcher)
                        .showImageOnLoading(R.mipmap.ic_launcher)
                        .build())
                .build());


    }
}