1、自定义SmartImageView 继承ImageView:
public class SmartImageView extends ImageView { public Context mContext; protected static final int SUCCESS = 1; public SmartImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public SmartImageView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; } Handler handler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case SUCCESS: Bitmap bitmap =(Bitmap)msg.obj; setImageBitmap(bitmap); break; default: //获取图片失败 Toast.makeText(mContext, "图片获取失败", 0).show(); break; } }; }; public SmartImageView(Context context) { super(context); } public void setImageUri(final String path) { new Thread(){ public void run() { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.setRequestMethod("GET"); int code = conn.getResponseCode(); if (code == 200) { InputStream is = conn.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(is); Message msg = Message.obtain(); msg.obj = bitmap; msg.what =SUCCESS; handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); handler.sendEmptyMessage(0); } }; }.start(); } }
2、布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <com.tang.smartimageview.SmartImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:src="@drawable/ic_launcher" /> </RelativeLayout>
3、MainActivity使用SmartImageView:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SmartImageView iv = (SmartImageView) findViewById(R.id.imageView1); iv.setImageUri("http://a.hiphotos.baidu.com/image/w%3D310/sign=3cb1bd0e369b033b2c88fadb25cf3620/3801213fb80e7becbc7ca3eb2d2eb9389b506b12.jpg"); } }