图片加载步骤
使用之前加上网络权限
<uses-permission android:name="android.permission.INTERNET" />
- 绑定ID,监听按钮
- 因为有传值的需求,所以我们重新建立了ImgLoadTask方法继承AsyncTask
- doInBackground方法,加载网络图片,最后获取到一个Bitmap对象,返回Bitmap对象
- 在doInbackground方法中运用try方法,把输入流转换成Bitmap类型对象
- onPostExexcute方法
- 在按钮的监听中绑定ImgLoadTask方法,添加图片地址,运行
代码展示
ImgLoadTask:
public class ImgLoadTask extends AsyncTask<String,Integer,Bitmap>{
private ImageView imageView;
//为什么要加一个构造方法,因为我们有传值的需求
public ImgLoadTask(ImageView iv){
this.imageView=iv;
}
@Override
protected Bitmap doInBackground(String... strings) {
//加载网络图片,最后获取到一个Bitmap对象,返回Bitmap对象
Bitmap bm=null;
try {
URL url=new URL(strings[0]);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
InputStream inputStream=connection.getInputStream();
bm= BitmapFactory.decodeStream(inputStream);//把输入流转换成Bitmap类型对象
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
@Override
protected void onPostExecute(Bitmap s) {
super.onPostExecute(s);
imageView.setImageBitmap(s);
}
}
ImgActivity:
public class ImgActivity extends AppCompatActivity {
private Button loadbtn;
private ImageView loadimg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_img);
bindID();
loadbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImgLoadTask task=new ImgLoadTask(loadimg);
task.execute("http://img31.mtime.cn/mg/2012/10/30/201631.37192876.jpg");
}
});
}
private void bindID() {
loadbtn=findViewById(R.id.loadpic_btn);
loadimg=findViewById(R.id.loadpic_img);
}
}