实现imageview直接利用url实现加载图片

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.ImageView;


public class SmartImageView extends ImageView{







public SmartImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public SmartImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SmartImageView(Context context) {
super(context);
}

private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
Bitmap bm = (Bitmap) msg.obj;
SmartImageView.this.setImageBitmap(bm);
};
};
public void setImageUrl(final String path){

if(TextUtils.isEmpty(path)){
return;
}else{
new Thread(){
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if(code == 200){
InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);

Message msg = Message.obtain();
msg.obj = bm;

handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();

}

}


}



<com.itheima.smartimageview.SmartImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       
        android:id="@+id/iv" />


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

iv = (SmartImageView) findViewById(R.id.iv);
iv.setImageUrl("http://pic.hao123.com/");
}
























































评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值