安卓開發:SmartImageView簡單實現和應用

來源:互聯網
上載者:User

標籤:重載方法   else   roi   方法   wrap   raw   widget   分享   dstat   

通常從伺服器端擷取的圖片是URL地址,如果簡單地通過URL地址擷取圖片?

有一個開源項目:SmartImageView,做到了這個功能,同時還有其他功能,下載不便,過於龐大

這裡自己實現它的這個簡易功能

 

代碼:

package org.dreamtech.smartimageview;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import android.annotation.SuppressLint;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;public class MySmartImageView extends ImageView {    protected static final int REQUESTSUCCESS = 1;    protected static final int REQUESTFAIL = 2;    protected static final int ERROR = 3;    @SuppressLint("HandlerLeak")    private Handler handler = new Handler() {        public void handleMessage(android.os.Message msg) {            switch (msg.what) {            case REQUESTSUCCESS:                Bitmap bitmap = (Bitmap) msg.obj;                MySmartImageView.this.setImageBitmap(bitmap);                break;            case REQUESTFAIL:                int default_resource = (Integer) msg.obj;                MySmartImageView.this.setBackgroundResource(default_resource);                break;            case ERROR:                int resource = (Integer) msg.obj;                MySmartImageView.this.setBackgroundResource(resource);                break;            }        };    };    // The construction methods of the parent class    public MySmartImageView(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);    }    public MySmartImageView(Context context, AttributeSet attrs) {        super(context, attrs);    }    public MySmartImageView(Context context) {        super(context);    }    // A method of displaying pictures    // path:The parameters of URL transmission    public void setImageUrl(final String path) {        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 in = conn.getInputStream();                        Bitmap bitmap = BitmapFactory.decodeStream(in);                        Message msg = Message.obtain();                        msg.obj = bitmap;                        handler.sendMessage(msg);                    }                } catch (Exception e) {                    e.printStackTrace();                }            };        }.start();    }    // A method of displaying pictures(Overloading method)    // path:The parameters of URL transmission    // resource:Default resources(If you can‘t find a resource through this URL)    public void setImageUrl(final String path, final int resource) {        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 in = conn.getInputStream();                        Bitmap bitmap = BitmapFactory.decodeStream(in);                        Message msg = Message.obtain();                        msg.what = REQUESTSUCCESS;                        msg.obj = bitmap;                        handler.sendMessage(msg);                    } else {                        Message msg = Message.obtain();                        msg.what = REQUESTFAIL;                        msg.obj = resource;                        handler.sendMessage(msg);                    }                } catch (Exception e) {                    Message msg = Message.obtain();                    msg.what = ERROR;                    msg.obj = resource;                    handler.sendMessage(msg);                }            };        }.start();    }}

 

 

兩個重載方法:

1:明確URL地址正確、不會失誤,直接調用

2:防止圖片URL出錯,設定預設資源,傳兩個參數

 

測試下:

package org.dreamtech.smartimageview;import android.os.Bundle;import android.app.Activity;import android.view.Menu;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        MySmartImageView iv = (MySmartImageView) findViewById(R.id.iv);        iv.setImageUrl(                "http://fanyi.bdstatic.com/static/translation/img/header/logo_cbfea26.png",                R.drawable.default_ic);    }}

 

布局:

<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"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <org.dreamtech.smartimageview.MySmartImageView        android:id="@+id/iv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"         /></RelativeLayout>

 

 

這裡是一個正確地URL地址,結果如下:

 

 

接下來,我把URL地址改成錯誤的:

 

結果:

 

好的,完成!

安卓開發:SmartImageView簡單實現和應用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.