在原生的ImageView中,没有一个方法是可以直接显示网络的图片的,当我们经常需要显示网络图片时,每次都有一大堆的操作,这会很麻烦,今天就教大家在ImageView上轻松显示网络图片。
自定义ImageView方法
写一个类让它继承ImageView,并增加一个setImageURL(path)方法
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MyImageView extends ImageView {
public static final int GET_DATA_SUCCESS = 1;
public static final int NETWORK_ERROR = 2;
public static final int SERVER_ERROR = 3;
//子线程不能操作UI,通过Handler设置图片
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case GET_DATA_SUCCESS:
Bitmap bitmap = (Bitmap) msg.obj;
setImageBitmap(bitmap);
break;
case NETWORK_ERROR:
Toast.makeText(getContext(),"网络连接失败",Toast.LENGTH_SHORT).show();
break;
case SERVER_ERROR:
Toast.makeText(getContext(),"服务器发生错误",Toast.LENGTH_SHORT).show();
break;
}
}
};
public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyImageView(Context context) {
super(context);
}
public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
//设置网络图片
public void setImageURL(final String path) {
//开启一个线程用于联网
new Thread() {
@Override
public void run() {
try {
//把传过来的路径转成URL
URL url = new URL(path);
//获取连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//使用GET方法访问网络
connection.setRequestMethod("GET");
//超时时间为10秒
connection.setConnectTimeout(10000);
//获取返回码
int code = connection.getResponseCode();
if (code == 200) {
InputStream inputStream = connection.getInputStream();
//使用工厂把网络的输入流生产Bitmap
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
//利用Message把图片发给Handler
Message msg = Message.obtain();
msg.obj = bitmap;
msg.what = GET_DATA_SUCCESS;
handler.sendMessage(msg);
inputStream.close();
}else {
//服务启发生错误
handler.sendEmptyMessage(SERVER_ERROR);
}
} catch (IOException e) {
e.printStackTrace();
//网络连接错误
handler.sendEmptyMessage(NETWORK_ERROR);
}
}
}.start();
}
}
在布局上不能使用ImageView,要使用MyImageView,要把刚才重写的一个MyImageView的全路径写上
<Button
android:text="加载网络图片"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button" />
<com.example.dell.myapplication.MyImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
在MainActivity上,只要调用setImageURL(),直接把网络的图片路径写上就可以显示网络的图片了
final MyImageView myImageView = (MyImageView) findViewById(R.id.image_view);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//直接把网络的图片路径写上就可以显示网络的图片了
myImageView.setImageURL("https://pic.cnblogs.com/avatar/1142647/20170416093225.png");
}
});