用HTTPURLConnecttion 加载网络图片
程序员文章站
2022-05-28 12:21:40
...
首先要分清思路,大概的流程是什么?
package com.example.lenovo.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private Button button;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.main_button);
imageView=findViewById(R.id.main_ImageView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Demo task=new Demo(MainActivity.this,button,imageView);
task.execute("http://img31.mtime.cn/mg/2012/10/30/201631.37192876.jpg");
}
});
}
}
我们要创建一个外部类Demo.java 更清晰更方便的 使用这个方法
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.BitSet;
/**
* Created by lenovo on 2018/3/13.
*/
public class Demo extends AsyncTask<String,Integer,Integer>{
private ImageView imageView;
private Bitmap bitmap;
public Demo(MainActivity mainActivity, Button button, ImageView imageView){
this.imageView=imageView;
}
@Override
protected Integer doInBackground(String... strings) {
try{
URL url=new URL(strings[0]);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
InputStream inputStream=httpURLConnection.getInputStream();
bitmap= BitmapFactory.decodeStream(inputStream);//将输入流转换成bitmap类型对象
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
switch (result) {
case 1:
imageView.setImageBitmap(bitmap);
break;
default:
break;
}
}
}
XML里 我们写简单的控件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.example.lenovo.myapplication.MainActivity">
<Button
android:textSize="25dp"
android:text="加载网络图片"
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="@+id/main_button"
/>
<ImageView
android:id="@+id/main_ImageView"
android:layout_marginTop="15dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
/>
</LinearLayout>
效果图:
上一篇: 创建工具类来完成我们的外部调用 一些修复加载图片的错乱代码
下一篇: 原生态图片上传与加载