Android 顯示網狀圖片

來源:互聯網
上載者:User

標籤:des   android   style   class   blog   code   

本文內容
  • 環境
  • 示範顯示網狀圖片

本文示範 Android 如何顯示網狀圖片。學習一門新的語言,最好辦法就先瞭解該語言的文法和庫,以及設計思想,再著手現實一些常用功能,畢竟以後用該語言是要寫程式的,而程式說白了,就是一個個功能點。

環境
  • Windows 2008 R2 64 位元
  • Eclipse ADT V22.6.2,Android 4.4.3
  • 三星 SM-G3508

 

示範顯示網狀圖片

利用一個新線程載入並顯示網狀圖片,並使用 handler 傳遞訊息,若無異常,則用 Toast 現實“載入圖片….”,否則,若網狀圖片不存在,顯示“圖片不存在”。同時,自訂一個類 HttpUtils,負責用 HTTP 訪問網路。Android 程式如所示。

圖 1

XML 分頁檔略,只是添加 ImageView 和 Button 控制項,核心代碼如下:

自訂 HttpUtils 類

使用 HTTP 協議訪問網狀圖片。

package com.example.viewwebimagedemo.utils;
 
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class HttpUtils {
 
    private final static String URL_PATH = "http://images.cnblogs.com/cnblogs_com/liuning8023/588559/o_Android.jpg";
 
    public HttpUtils() {
        // TODO Auto-generated constructor stub
    }
 
    public static InputStream getImageViewInputStream() throws IOException {
        InputStream inputStream = null;
 
        URL url = new URL(URL_PATH);
        if (url != null) {
            HttpURLConnection httpURLConnection = (HttpURLConnection) url
                    .openConnection();
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoInput(true);
            int response_code = httpURLConnection.getResponseCode();
            if (response_code == 200) {
                inputStream = httpURLConnection.getInputStream();
            }
        }
        return inputStream;
    }
}
MainActivity 類

負責載入並顯示網狀圖片。

package com.example.viewwebimagedemo;
 
import java.io.InputStream;
 
import com.example.viewwebimagedemo.R;
import com.example.viewwebimagedemo.utils.HttpUtils;
 
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
 
public class MainActivity extends Activity {
    private Button button;
    private ImageView imageView;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        button = (Button) this.findViewById(R.id.btn);
        imageView = (ImageView) this.findViewById(R.id.imageView);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(access).start();
            }
        });
    }
 
    // 獲得圖片
    public void getImg() {
        try {
            InputStream inputStream = HttpUtils.getImageViewInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            Looper.prepare();// 必須調用此方法,要不然會報錯
            Message msg = new Message();
            msg.what = 0;
            msg.obj = bitmap;
            handler.sendMessage(msg);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "擷取圖片錯誤", 1).show();
        }
    }
 
    // 載入圖片
    private void setImg(Bitmap bm) {
        imageView.setImageBitmap(bm);
    }
 
    // 另一個線程從網路獲得圖片
    private Runnable access = new Runnable() {
        @Override
        public void run() {
            getImg();
        }
    };
    // 更新UI資訊
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                if (msg.obj == null) {
                    Toast.makeText(getApplicationContext(), "圖片不存在", 1).show();
                } else {
                    Toast.makeText(getApplicationContext(), "載入圖片...", 1)
                            .show();
                    setImg((Bitmap) msg.obj);
                }
            }
        }
    };
}
授權 Android 訪問網路許可權

修改 AndroidManifest.xml 檔案,添加授權 Android 訪問網路的許可權。

    <uses-permission android:name="android.permission.INTERNET" />

 

若直接在 Activity 的 onCreate 事件裡載入並顯示圖片,如下所示:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        // 假設已經從網路獲得 bitmap
        imageView = (ImageView) this.findViewById(R.id.imageView);
        imageView.setImageBitmap(bitmap);
    }

會報 android.os.NetworkOnMainThreadException 異常。因為,Android 4.x 之後,不允許在主線程進行網路訪問。

 

下載 Demo

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.