AndroidJava网络加载框架Retrofit(二)load bitmap into ListView

xiaoxiao2021-02-28  7

Android/Java网络加载框架Retrofit(二)load bitmap into ListView

package zhangphil.http; import android.app.ListActivity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import java.util.ArrayList; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.http.GET; import retrofit2.http.Path; public class MainActivity extends ListActivity { private MyRetrofitService mRetrofitService; private ArrayList<Call> mCalls = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Retrofit mRetrofit = new Retrofit.Builder() .baseUrl("https://www.baidu.com/") .build(); mRetrofitService = mRetrofit.create(MyRetrofitService.class); ArrayAdapter mArrayAdapter = new ArrayAdapter(this, 0) { @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { ImageView imageView = new ImageView(getContext()); setBitmap("bd_logo1.png", imageView); return imageView; } @Override public int getCount() { return 10; } }; setListAdapter(mArrayAdapter); } private void setBitmap(String picName, final ImageView imageView) { final Call mCall = mRetrofitService.getImagesByName(picName); mCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { Log.d("请求的网络链接", String.valueOf(mCall.request().url())); byte[] bytes = response.body().bytes(); Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); imageView.setImageBitmap(bmp); } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); } }); mCalls.add(mCall); } private interface MyRetrofitService { @GET("img/{picName}") Call<ResponseBody> getImagesByName(@Path("picName") String picName); } @Override protected void onDestroy() { super.onDestroy(); for (Call call : mCalls) { call.cancel(); } } }

转载请注明原文地址: https://www.6miu.com/read-1400021.html

最新回复(0)