zoukankan      html  css  js  c++  java
  • 使用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"/>
  • 相关阅读:
    安卓手机!用swiper做轮播效果,两张图片之间会有一个像素的空白
    手机端swiper快速滑动会有白屏
    axios请求下载excel文件
    人人都能学会的webpack5搭建vue3项目(二)配置Vue
    人人都能学会的webpack5搭建vue3.0项目,可应用于生产环境 (一)
    mybatis 生成 mapper文件
    超强工具类系列
    mybatis 自动生成mapper文件
    面试
    linux安装mysql8.0.25
  • 原文地址:https://www.cnblogs.com/weifengzz/p/5012780.html
Copyright © 2011-2022 走看看