從網路獲取圖片並載入到ImageView
阿新 • • 發佈:2019-02-10
佈局檔案:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="30dp" android:text="從網路獲取圖片" android:layout_marginLeft="120dp" /> <ImageView android:id="@+id/img" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/button" /> </RelativeLayout>
public class MainActivity extends AppCompatActivity { private String imageUrl = "http://news.sciencenet.cn/upload/news/images/2011/3/20113301123128272.jpg"; private Button button; private ImageView img; //在訊息佇列中實現對控制元件的更改 private Handler handle = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 0: Bitmap bmp=(Bitmap)msg.obj; img.setImageBitmap(bmp); break; } }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); img = (ImageView) findViewById(R.id.img); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //新建執行緒載入圖片資訊,傳送到訊息佇列中 new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub Bitmap bmp = getURLimage(imageUrl); Message msg = new Message(); msg.what = 0; msg.obj = bmp; handle.sendMessage(msg); } }).start(); } }); } private Bitmap getURLimage(String imageUrl) { Bitmap bmp = null; try { URL myurl = new URL(imageUrl); // 獲得連線 HttpURLConnection conn = (HttpURLConnection) myurl.openConnection(); conn.setConnectTimeout(6000);//設定超時 conn.setDoInput(true); conn.setUseCaches(false);//不快取 conn.connect(); InputStream is = conn.getInputStream();//獲得圖片的資料流 bmp = BitmapFactory.decodeStream(is); is.close(); } catch (Exception e) { e.printStackTrace(); } return bmp; } }