Android开发学习:[22]获取网络图片
1、首先我们打开我们下载安装好的Android Studio新建好项目
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" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="com.basillee.asus.demo.MainActivity3"><ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"></ImageView></RelativeLayout>主要就是在屏幕中央添加一个ImageView控件
3、然后我们编写一个getPicture()方法用来返回一个Bitmap对象,用来获取网络图片: public Bitmap getPicture(String path){ Bitmap bm=null; try{ URL url=new URL(path); URLConnection connection=url.openConnection(); connection.connect(); InputStream inputStream=connection.getInputStream(); bm= BitmapFactory.decodeStream(inputStream); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bm; }
4、然后我们在oncreate方法中添加一个新线程:protected void onCreate(Bundle savedInst锾攒揉敫anceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_activity3); imageView= (ImageView) findViewById(R.id.imageView); new Thread(new Runnable() { @Override public void run() { final Bitmap bitmap=getPicture("http://h.hiphotos.baidu.com/news/q%3D100/sign=be8e90f30cfa513d57aa68de0d6d554c/c75c10385343fbf29d10a30cb47eca8065388fe4.jpg"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } imageView.post(new Runnable() { @Override public void run() { imageView.setImageBitmap(bitmap); } }); } }).start(); }
5、编写好了之后我们打开虚拟机
6、然后运行此项目我们可以看到图片显示在屏幕中央