1. 程式人生 > >網路載入圖片 展示圖片 樣式

網路載入圖片 展示圖片 樣式

MainActivity

package com.example.imageloader;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;

import com.nostra13.universalimageloader.core.ImageLoader;

public class MainActivity extends AppCompatActivity {

    private ListView news;
    private MyBaseAdafter mAdapter;

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

        news = findViewById(R.id.news);
        mAdapter = new MyBaseAdafter(this);
        news.setAdapter(mAdapter);

        findViewById(R.id.left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //載入資料
                NetUtil.getInstance().getRequest("http://api.expoon.com/AppNews/getNewsList/type/1/p/1", Bean.class, new NetUtil.Callbak<Bean>() {
                    @Override
                    public void onSuccess(Bean o) {
                        mAdapter.setListData(o.getData());
                    }
                });
            }
        });
    }
}

BaseAdapter頁面

package com.example.imageloader;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.BitmapDisplayer;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

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

public class MyBaseAdafter extends BaseAdapter {
    private Context context;
    private List<Bean.DataBean>mlist;

    public MyBaseAdafter(Context context) {
        this.context = context;
        mlist = new ArrayList<>();
    }
public void setListData(List<Bean.DataBean> list){
        this.mlist = list;
        notifyDataSetChanged();
}
    @Override
    public int getCount() {
        return mlist.size();
    }

    @Override
    public Bean.DataBean getItem(int position) {
        return mlist.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHoder viewHoder;
        if(convertView==null){
            convertView = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
            viewHoder = new ViewHoder();
            viewHoder.textView1 = convertView.findViewById(R.id.textview1);
            viewHoder.textView2 = convertView.findViewById(R.id.textview2);
            viewHoder.imageView = convertView.findViewById(R.id.imageview);
            convertView.setTag(viewHoder);
        }else{
            viewHoder = (ViewHoder) convertView.getTag();
        }
        viewHoder.textView1.setText(mlist.get(position).getNews_title());
        viewHoder.textView2.setText(mlist.get(position).getNews_summary());

        // 1280 * 720   -> 1280 * 720   *   每個畫素佔用位元組數16
        //

        //RGB_565       red green blue     紅綠藍 的顏色      r佔5byte   g佔6byte    b佔5byte
        //A RGB_4444 A RGB_8888
        //ALPHA_8

        //BitmapDisplayer

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                //配置色彩模式
                .bitmapConfig(Bitmap.Config.RGB_565)
                //配置  是否快取
                .cacheInMemory(true)
                .cacheOnDisk(true)
                //配置 預設顯示
                .showImageOnLoading(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher)
                .showImageForEmptyUri(R.mipmap.ic_launcher)

                //配置圖片如何縮放
                .imageScaleType(ImageScaleType.EXACTLY)

                //顯示效果:圓形
                //.displayer(new CircleBitmapDisplayer())
                //圓角
                //.displayer(new RoundedBitmapDisplayer(8))
                .displayer(new FadeInBitmapDisplayer(2000))
                .build();

       //載入圖片
        ImageLoader
                .getInstance()
                .displayImage(getItem(position).getPic_url(), viewHoder.imageView, options);

        //只加載圖片
        //回撥返回bitmap
        //ImageLoader.getInstance().loadImage();

        return convertView;
    }
    class ViewHoder{
        private TextView textView1,textView2;
        private ImageView imageView;
    }
}

工具類NetUtil

package com.example.yu.zixun01;
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.URL;
import java.util.List;

public class NetUtil {
    private static NetUtil netUtil;

    public static NetUtil getInstance(){
        if(netUtil==null){
            netUtil=new NetUtil();
        }
        return netUtil;
    }

    public interface CallBack<T>{
        void onsuccess(T t);
    }
    @SuppressLint("StaticFieldLeak")
    public void getRequest(final String strurl, final Class bean, final CallBack callBack) {
        new AsyncTask<String, Void, Object>() {
            @Override
            protected Object doInBackground(String... strings) {

                return getRequest(strurl,bean);
            }

            @Override
            protected void onPostExecute(Object o) {
                callBack.onsuccess(o);
            }
        }.execute(strurl, "");
    }

    public <T> T getRequest(String urlStr,Class clazz){
        return (T) new Gson().fromJson(getRequest(urlStr),clazz);
    }
    public String getRequest(String strurl){
        String result = "";
        try {
            URL url = new URL(strurl);
            HttpURLConnection urlConnection = null;
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(5000);
            urlConnection.setReadTimeout(5000);
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == 200) {
                result = stream2String(urlConnection.getInputStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    public String stream2String(InputStream inputStream) throws IOException {
        StringBuilder sb = new StringBuilder();

        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        for (String tmp = br.readLine(); tmp != null; tmp = br.readLine()) {
            sb.append(tmp);
        }
        return sb.toString();
    }
}

Bean類

   package com.example.imageloader;

import java.util.List;

public class Bean {

    /**
     * status : 1
     * info : 獲取內容成功
     * data : [{"news_id":"13811","news_title":"深港澳臺千里連線,嘉年華會今夏入川","news_summary":"6月17\u201420日,\u201c2016成都深港澳臺嘉年華會\u201d(簡稱嘉年華會)將在成都世紀城國際會展中心舉辦。其主辦方勵展華博借力旗","pic_url":"http://f.expoon.com/sub/news/2016/01/21/887844_230x162_0.jpg"},]
     */

    private List<DataBean> data;

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        /**
         * news_id : 13811
         * news_title : 深港澳臺千里連線,嘉年華會今夏入川
         * news_summary : 6月17—20日,“2016成都深港澳臺嘉年華會”(簡稱嘉年華會)將在成都世紀城國際會展中心舉辦。其主辦方勵展華博借力旗
         * pic_url : http://f.expoon.com/sub/news/2016/01/21/887844_230x162_0.jpg
         */

        private String news_title;
        private String news_summary;
        private String pic_url;

        public String getNews_title() {
            return news_title;
        }

        public void setNews_title(String news_title) {
            this.news_title = news_title;
        }

        public String getNews_summary() {
            return news_summary;
        }

        public void setNews_summary(String news_summary) {
            this.news_summary = news_summary;
        }

        public String getPic_url() {
            return pic_url;
        }

        public void setPic_url(String pic_url) {
            this.pic_url = pic_url;
        }
    }
}

App頁面

package com.example.imageloader;

import android.app.Application;
import android.os.Environment;

import com.nostra13.universalimageloader.cache.disc.DiskCache;
import com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.MemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import java.io.IOException;

//優先於所有頁面(Activity)建立
//主要負責應用全域性初始化
//該物件也是一個context
public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        //ctrl + h 檢視累的繼承結構
        //MemoryCache

        //DiskCache

        //FileNameGenerator

        //怎麼呼叫api
        //要什麼引數
        //怎麼給這個引數

        //Builder
        //構建模式
        //鏈式呼叫
        //全域性配置
        ImageLoaderConfiguration configuration = null;
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .build();
        //try {

        //
            configuration = new ImageLoaderConfiguration.Builder(this)
                    //配置:記憶體 磁碟 快取
                    //.memoryCache(new LruMemoryCache())
                    //.memoryCacheSize()
                    //記憶體快取大小
                    .memoryCacheSizePercentage(10)
                    //配置磁碟快取:目錄 檔名生成  大小
                    //.diskCache(new LruDiskCache(getCacheDir(), new HashCodeFileNameGenerator(), 10*1024*1024))
                    .diskCacheSize(50*1024*1024)
                    //執行緒配置
                    //任務優先順序配置
                    //FIFO
                    //載入圖片1   2  3  4  5
                    //LIFO
                    //.tasksProcessingOrder(QueueProcessingType.)
                    //預設顯示配置
                    //.defaultDisplayImageOptions(options)
                    .build();
        //} catch (IOException e) {
        //    e.printStackTrace();
        //}

        //初始化:只有第一次初始化有效果
        ImageLoader.getInstance().init(configuration);

        //無效果
        //ImageLoader.getInstance().init(null);
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.imageloader">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:name=".App"//註冊activity
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

需要第三方jar包 gson , image-loader