使用OkHttp网络请求+Fresco图片显示把请求到的数据展示到ListView上

最近一直在用Recyclerview展示数据,导致了ListView不怎么会用了,今天就来复习一下ListView

先看一下今天要展示的效果


先是最最最重要的依赖,没有依赖啥事也做不了

compile 'com.squareup.okhttp3:okhttp:3.9.0'
    compile 'com.google.code.gson:gson:2.6.1'
    compile 'com.facebook.fresco:fresco:0.9.0+'

下面就是代码,先是两个布局

activity_main这里面就一个ListView

<RelativeLayout 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="bwie.com.diertianjineng_1227.MainActivity">

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

</RelativeLayout>

下面是list_item这里面用到了SimpleDraweeView

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    >
    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/sv"
        android:layout_width="120dp"
        android:layout_height="120dp"
        fresco:placeholderImage="@mipmap/ic_launcher"
        />

    <TextView
        android:id="@+id/tv1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="5dp"
        android:layout_toEndOf="@+id/sv" />

    <TextView
        android:id="@+id/tv2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv1"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="18dp"
        android:layout_toEndOf="@+id/sv" />
</RelativeLayout>

下面就是代码 MainActivity

我这个人有点懒,就把适配器给写到了MainActivity里面了,写在外面也一样

import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    String str="http://120.27.23.105/ad/getAd";
    ListView lv;
    Bean bean;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv=findViewById(R.id.lv);
        okURL();
    }
    //okhttp的网络请求
    private void okURL() {
        OkHttp3Utils.doGet(str, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //Gson解析
                Gson gson = new Gson();
                String strs = response.body().string();
                bean = gson.fromJson(strs, Bean.class);
                //判断call,如果返回ture就继续执行,否则就不行
                if (response.isSuccessful()) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //创建适配器
                            MyArder adapter = new MyArder();
                            //设置适配器
                            lv.setAdapter(adapter);
                            //刷新适配器
                            adapter.notifyDataSetChanged();
                        }
                    });
                }

            }
        });
    }
    //
    class MyArder extends BaseAdapter{

        @Override
        public int getCount() {
            return bean.getData().size();
        }

        @Override
        public Object getItem(int position) {
            return bean.getData().get(position);
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            //初始化holder对象
            ViewHolder holder;
            if (convertView==null){
                //把条目布局转化为view对象
                convertView=View.inflate(MainActivity.this,R.layout.list_item,null);
                //初始化holder对象,并初始化holder中的控件
                holder=new ViewHolder();
                holder.tv1=convertView.findViewById(R.id.tv1);
                holder.tv2=convertView.findViewById(R.id.tv2);
                holder.sv=convertView.findViewById(R.id.sv);
                //给当前view做个标记,并把数据存到该tag中
                convertView.setTag(holder);
            }else {
                //如果当前view存在,则直接从中取出其保存的控件及数据
                holder=(ViewHolder) convertView.getTag();
            }


            holder.tv1.setText(bean.getData().get(position).getTitle());
            holder.tv2.setText(bean.getData().get(position).getCreatetime());
            //设置图片是否是圆形
            RoundingParams params = RoundingParams.asCircle();
            GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(getResources());
            GenericDraweeHierarchy hierarchy = builder.setRoundingParams(params).build();
            holder.sv.setHierarchy(hierarchy);
            holder.sv.setImageURI(Uri.parse(bean.getData().get(position).getIcon()));

            return convertView;
        }
        /*
        * 用来存放item布局中控件的holder类
        */
        class ViewHolder{
            TextView tv1,tv2;
            SimpleDraweeView sv;
        }
    }
}

下面是OkHttp类

import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by BAIPEI on 2017/12/27.
 */

public class OkHttp3Utils {
    private static OkHttpClient okHttpClient = null;

    public OkHttp3Utils() {
    }

    private static OkHttpClient getOkHttpClient() {
        synchronized (OkHttp3Utils.class) {
            if (okHttpClient == null) {
                okHttpClient = new OkHttpClient();
            }
        }
        return okHttpClient;
    }

    //上传文件
    public static void loadFile(String url, File file, String fileName){
        OkHttpClient okHttpClient = getOkHttpClient();
        //设置文件类型
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"),file);
        //设置请求体
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image",fileName,requestBody)
                .build();
        //请求方式
        Request request = new Request.Builder().url(url).post(body).build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("成功","成功");
            }
        });
    }

    /**
     * 1.接口地址
     * 2.接口回调
     */
    public static void doGet(String url,Callback callback){
        OkHttpClient okHttpClient = getOkHttpClient();
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 1.地址
     * 2.接口回调
     * 3.请求体
     */

    public static void doPost(String url, Map<String,String> map, Callback callback){
        OkHttpClient okHttpClient = getOkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        //遍历map集合   设置请求体
        for (String mapKey : map.keySet()){
            builder.add(mapKey,map.get(mapKey));
        }
        //设置请求方式
        Request request = new Request.Builder().url(url).post(builder.build()).build();
        //执行请求方式    接口回调
        okHttpClient.newCall(request).enqueue(callback);
    }

    /**
     *1.下载地址
     */
    public static void doDown(String url,Callback callback){
        OkHttpClient okHttpClient = getOkHttpClient();
        Request build = new Request.Builder().url(url).build();

        okHttpClient.newCall(build).enqueue(callback);
    }
}

Bean类就不粘了

Fresco必须要初始化所以就创了个他的初始化类

import android.app.Application;


import com.facebook.drawee.backends.pipeline.Fresco;


/**
 * Created by BAIPEI on 2017/12/27.
 */

public class MyApplication extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);
    }
}









要在 ListView 显示多张图片,可以使用 OkHttp 进行网络请求获取图片,并使用 ViewHolder 模式对 ListView 进行优化,以提高列表的滑动流畅性。具体实现步骤如下: 1. 在 Adapter 定义 ViewHolder,用于缓存 item 的控件: ```java private static class ViewHolder { ImageView imageView; } ``` 2. 在 getView() 方法获取 ViewHolder,如果 convertView 为 null,则新建一个 ViewHolder,并使用 LayoutInflater 加载布局文件: ```java @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate(R.layout.item_layout, parent, false); holder = new ViewHolder(); holder.imageView = convertView.findViewById(R.id.image_view); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // 加载图片设置到 ImageView loadImage(holder.imageView, imageUrlList.get(position)); return convertView; } ``` 3. 在 loadImage() 方法使用 OkHttp 进行网络请求获取图片设置到 ImageView : ```java private void loadImage(final ImageView imageView, String imageUrl) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(imageUrl) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream inputStream = response.body().byteStream(); final Bitmap bitmap = BitmapFactory.decodeStream(inputStream); mHandler.post(new Runnable() { @Override public void run() { imageView.setImageBitmap(bitmap); } }); } }); } ``` 其,`imageUrlList` 是存储图片 URL 地址的列表,`mContext` 是 Context 对象,`mHandler` 是 Handler 对象,用于在子线程更新 UI。首先创建一个 OkHttpClient 对象,然后使用 Request.Builder 构建一个请求设置请求的 URL 地址。接着使用 `newCall(request).enqueue()` 方法异步执行请求,并在回调方法获取响应的结果,将 InputStream 转换成 Bitmap,并使用 Handler 将 Bitmap 设置到 ImageView ,以更新 UI。 需要注意的是,由于网络请求是异步执行的,因此需要使用 Handler 来更新 UI,否则会出现异常。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值