1 2 3
| InputStream in = (InputStream) new URL("http://xxx.jpg").openStream(); final Drawable d = Drawable.createFromStream(in, "src"); in.close();
|
以下示例给linearlayout设置网络图片为背景
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| linear=(LinearLayout)findViewById(R.id.linear); new Thread(new Runnable() { @Override public void run() { try { InputStream in = (InputStream) new URL("http://xxx.jpg").openStream(); final Drawable d = Drawable.createFromStream(in, "src"); in.close(); runOnUiThread(new Runnable() { @Override public void run() { linear.setBackground(d); } }); } catch (IOException e) { e.printStackTrace(); } } }).start();
|
注意,http请求需要在子线程中完成,UI更新需要在主线程中完成
android9.0以上版本中允许http请求需要在AndroidManifest.xml中的application标签中添加
android:usesCleartextTraffic=”true”