【0038】Android基础-26-开源项目smartImageView的使用及实现原理(接上节新闻客户端的网络实现)

【1】自定义控件在使用时,需要在引用时需要写明完整的包名路径

 

【2】ImageView控件在显示的时候,没有将设定的像素填充完整

【改进】设置ImageView的scaleType属性

【3】自己书写SmartView控件源码

【3.1】自定义控件必须实现3个构造方法,不然会报下面的异常

 

【3.2】图片数据请求有问题

 

 

 

【3.3】自定义的SmartImageView的原理

【3.4】自定义的SmartImageView的源码

 1 package com.itheima.news_listview.view;
 2 
 3 import java.io.InputStream;
 4 import java.net.HttpURLConnection;
 5 import java.net.URL;
 6 import java.net.URLConnection;
 7 
 8 import android.content.Context;
 9 import android.graphics.Bitmap;
10 import android.graphics.BitmapFactory;
11 import android.os.Handler;
12 import android.os.Message;
13 import android.util.AttributeSet;
14 import android.widget.ImageView;
15 
16 public class MyImageView extends ImageView {
17 
18     public MyImageView(Context context) {
19         super(context);
20     }
21     public MyImageView(Context context, AttributeSet attrs) {
22         super(context, attrs);
23     }
24     public MyImageView(Context context, AttributeSet attrs, int defStyle) {
25         super(context, attrs, defStyle);
26     }
27     
28     private Handler handler = new Handler(){
29         
30         public void handleMessage(android.os.Message msg) {
31             
32             Bitmap bitmap = (Bitmap) msg.obj;
33             
34             MyImageView.this.setImageBitmap(bitmap);
35         };
36     };
37 
38     public void setImageUrl(final String url_str){
39         
40         
41         new Thread(new Runnable() {
42             
43             @Override
44             public void run() {
45                 try{
46                     //获取url对应的图片资源,bitmap
47                     URL url = new URL(url_str);
48                     
49                     HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
50                     
51                     openConnection.setRequestMethod("GET");
52                     openConnection.setConnectTimeout(10*1000);
53                     
54                     int code = openConnection.getResponseCode();
55                     if(code == 200){
56                         InputStream inputStream = openConnection.getInputStream();
57                         
58                         
59                         Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
60                         
61                         Message msg = Message.obtain();
62                         msg.obj = bitmap;
63                         handler.sendMessage(msg);
64                         
65                         
66                     }
67                     
68                     
69                 }catch (Exception e) {
70                     e.printStackTrace();
71                 }
72             }
73         }).start();
74         
75     
76     }
77 
78 }

 

posted @ 2017-10-24 14:36  OzTaking  阅读(452)  评论(0)    收藏  举报