Android(安卓)异步加载图片
16lz
2021-12-04
1.运行后界面图:
2.主要代码
2.1 activity_main.xml 布局
1 <LinearLayout 2 android:layout_width="match_parent" 3 android:layout_height="50dp" 4 android:orientation="horizontal" > 5 6 <EditText 7 android:id="@+id/etUrl" 8 android:layout_width="166dp" 9 android:layout_height="wrap_content"10 android:layout_weight="0.65"11 android:text="http://img3.redocn.com/20100206/20100206_c3f11163684180e389c57LUEUjSMDaax.jpg"12 android:ems="10" />13 14 <Button15 android:id="@+id/btnLoad"16 android:layout_width="wrap_content"17 android:layout_height="wrap_content"18 android:onClick="ShowImg"19 android:text="加载" />20 </LinearLayout>21 22 <ImageView23 android:id="@+id/ivImg"24 android:layout_width="match_parent"25 android:layout_height="match_parent"26 android:src="@drawable/ic_launcher" />XML布局
2.2 MainActivity.java
1 private Handler handler=new Handler(){ 2 public void handleMessage(android.os.Message msg){ 3 switch (msg.what) { 4 case 1: 5 Bitmap bitmap=(Bitmap) msg.obj; 6 ivImg.setImageBitmap(bitmap); 7 break; 8 default: 9 break; 10 } 11 } 12 }; 13 //showImg14 public void ShowImg(View view){15 final String path = etUrl.getText().toString();16 if(!TextUtils.isEmpty(path)){17 new Thread(){18 public void run(){19 try{20 URL url = new URL(path);21 HttpURLConnection httpUrlConn = (HttpURLConnection)url.openConnection();22 httpUrlConn.setRequestMethod("GET");23 //超时24 httpUrlConn.setConnectTimeout(5000);25 int responseCode = httpUrlConn.getResponseCode();26 if(responseCode == 200){27 InputStream is = httpUrlConn.getInputStream();28 Bitmap bitmap = BitmapFactory.decodeStream(is);29 30 Message msg = new Message();31 msg.what=1;32 msg.obj = bitmap;33 handler.sendMessage(msg);34 }35 36 }catch(MalformedURLException e){37 e.printStackTrace();38 }catch(IOException e){39 e.printStackTrace();40 }41 }42 }.start();43 }else{44 Toast.makeText(this, "图片路径不能为空", Toast.LENGTH_LONG).show();45 }46 47 }48View Code
2.3 同样 在XML布局中找到Button注册一个onclick事件 引用MainActivity中的ShowImg方法
3. AndroidManifest.xml 中注册联网权限
<uses-permission android:name="android.permission.INTERNET"/>
4. demo
https://github.com/cnfanhua/A-AsynLoadPic
更多相关文章
- Android(安卓)10ms问题:关于Android音频路径延迟的解释
- 收集android的三个小tip
- Android(安卓)NDK: Your APP_BUILD_SCRIPT points to an unknown
- 收集android的三个小tip
- 收集android的三个小tip
- 收集android的三个小tip
- 收集android的三个小tip
- 收集android的三个小tip
- 收集android的三个小tip