使用AsyncTask实现图片加载
生活随笔
收集整理的這篇文章主要介紹了
使用AsyncTask实现图片加载
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如上圖所示:我們看到的就是使用PrograssDialog進度條和AsyncTask異步任務實現的效果(額,不要看應用名。。。)。下面介紹一下具體的實現流程。
一、首先使用XML布局,布局很簡單直接上代碼:
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 tools:context="com.weifengzz.httpclientdemo.MainActivity$PlaceholderFragment" > 6 7 <Button 8 android:id="@+id/getImage_btn" 9 android:layout_width="match_parent" 10 android:layout_height="wrap_content" 11 android:layout_alignParentLeft="true" 12 android:layout_below="@+id/img" 13 android:layout_marginTop="22dp" 14 android:text="獲取圖片" /> 15 16 <ImageView 17 android:id="@+id/img" 18 android:layout_width="200dp" 19 android:layout_height="200dp" 20 android:layout_alignParentTop="true" 21 android:layout_centerHorizontal="true" 22 android:scaleType="fitCenter" 23 android:src="@drawable/ic_launcher" /> 24 25 </RelativeLayout>二、MainActivity類主要就是對組件的初始化。
1 public class MainActivity extends Activity { 2 private Button button = null;// 按鈕 3 private ImageView imageView = null;// 圖片 4 private ProgressDialog progressDialog = null;// 進度條 5 private String imgPath = "http://images.ent.xunlei.com/660x1500/189/120818zknfkvg2vtpupxyjdruovsafnj7mbmikn5yh7mpe.jpg";// 圖片的地址 6 private DownLoadImage downLoadImage = null;// AsyncTask異步任務類 7 8 @Override 9 protected void onCreate(Bundle savedInstanceState) { 10 super.onCreate(savedInstanceState); 11 setContentView(R.layout.activity_main); 12 intView(); 13 //點擊加載圖片 14 button.setOnClickListener(new OnClickListener() { 15 16 @Override 17 public void onClick(View arg0) { 18 // TODO Auto-generated method stub 19 downLoadImage.execute(imgPath); 20 } 21 }); 22 } 23 24 /** 25 * 初始化組件 26 * */ 27 private void intView() { 28 button = (Button) findViewById(R.id.getImage_btn); 29 imageView = (ImageView) findViewById(R.id.img); 30 progressDialog = new ProgressDialog(MainActivity.this); 31 downLoadImage = new DownLoadImage(imageView, progressDialog); 32 } 33 }?三、DownLoadImage類的實現,此類繼承了 AsyncTask異步任務類
1 public class DownLoadImage extends AsyncTask<String, Integer, byte[]> { 2 private ProgressDialog progressDialog = null;//進度條 3 private ImageView iv = null; //圖片控件 4 5 public DownLoadImage(ImageView imageView,ProgressDialog progressDialog) { 6 this.progressDialog = progressDialog; 7 this.iv = imageView; 8 } 9 10 /** 11 * 首次調用的方法,通常我們在此方法中可以初始化一些組件 12 */ 13 @Override 14 protected void onPreExecute() { 15 // TODO Auto-generated method stub 16 super.onPreExecute(); 17 progressDialog.setTitle("下載");//設置標題 18 progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//設置樣式 19 progressDialog.setMessage("正在加載,請稍后...");//設置顯示的文字 20 progressDialog.show(); 21 } 22 23 /** 24 * 執行耗時的操作,請求網絡數據 String... params:可變的數組 25 */ 26 @Override 27 protected byte[] doInBackground(String... params) { 28 // TODO Auto-generated method stub 29 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 30 int temp = 0; 31 //使用HttpClient獲取數據 32 HttpClient httpClient = new DefaultHttpClient(); 33 HttpGet hg = new HttpGet(params[0]); 34 try { 35 HttpResponse httpResponse = httpClient.execute(hg); 36 if (httpResponse.getStatusLine().getStatusCode() == 200) { 37 InputStream inputStream = httpResponse.getEntity().getContent(); 38 long length = httpResponse.getEntity().getContentLength(); 39 int current = 0; 40 //每次讀10個字節,如果讀的字節數據比較多的話,進度條會顯示的不是那么流暢,會有很大的跳躍感 41 byte[] bt = new byte[10]; 42 //循環讀取數據 43 while ((temp = inputStream.read(bt)) != -1) { 44 //如果沒有取消就每循環一次更新一次進度條 45 if (!this.isCancelled()) { 46 current += temp; 47 publishProgress((int) ((current / (float) length) * 100)); 48 //輸出流 49 outputStream.write(bt, 0, temp); 50 } 51 } 52 } 53 } catch (ClientProtocolException e) { 54 // TODO Auto-generated catch block 55 e.printStackTrace(); 56 } catch (IOException e) { 57 // TODO Auto-generated catch block 58 e.printStackTrace(); 59 } 60 return outputStream.toByteArray(); 61 } 62 63 /** 64 * 調用完publishProgress之后會執行此方法,更新刻度 65 */ 66 @Override 67 protected void onProgressUpdate(Integer... values) { 68 // TODO Auto-generated method stub 69 super.onProgressUpdate(values); 70 progressDialog.setProgress(values[0]); 71 } 72 73 /** 74 * 運行在UI線程中 執行完doInbackgroud方法之后,系統會調用此方法, 并且把doInbackground方法返回的結果傳給此方法 75 */ 76 @Override 77 protected void onPostExecute(byte[] result) { 78 // TODO Auto-generated method stub 79 super.onPostExecute(result); 80 // 把byte數組轉成Bitmap位圖對象 81 Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length); 82 iv.setImageBitmap(bitmap); 83 // 關閉對話框 84 progressDialog.dismiss(); 85 } 86 }四、最后不要忘記添加網絡權限
1 <uses-permission android:name="android.permission.INTERNET"/>?
轉載于:https://www.cnblogs.com/weifengzz/p/5012780.html
總結
以上是生活随笔為你收集整理的使用AsyncTask实现图片加载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用Unity3D的50个技巧:Unity
- 下一篇: HTML5拖放(drag and dro