懒惰下载图片到GridView控件 [英] Lazy download images into gridView

查看:138
本文介绍了懒惰下载图片到GridView控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序需要从网址下载大量的图片,并在GridView显示出来。 (它可以是1-200画面之间)。我不想下载所有照片一次。我读到懒惰下载和我的问题是:我能得到JSON的只是其中的一部分,下载图片在不同的线程,且仅当用户向下滚动 GridView的,我会继续的JSON的其他部分,等等?

编辑:您好再次。我想实现这个GridView的多选择,我有困难,实现code在适配器的getView()方法。这是我使用的例子:<一href="http://www.java2s.com/$c$c/Android/UI/ThisdemoillustratestheuseofCHOICEMODEMULTIPLEMODALakaselectionmodeonGridView.htm"相对=nofollow>例如的。我怎么能在我的getView结合起来code()方法:

 公开查看getView(INT位置,查看convertView,ViewGroup中父){
        CheckableLayout升;
        ImageView的我;

        如果(convertView == NULL){
            I =新ImageView的(Grid3.this);
            i.setScaleType(ImageView.ScaleType.FIT_CENTER);
            i.setLayoutParams(新ViewGroup.LayoutParams(50,50));
            L =新CheckableLayout(Grid3.this);
            l.setLayoutParams(新GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT,
                    GridView.LayoutParams.WRAP_CONTENT));
            l.addView(ⅰ);
        } 其他 {
            L =(CheckableLayout)convertView;
            I =(ImageView的)l.getChildAt(0);
        }

        ResolveInfo信息= mApps.get(位置);
        i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));

        返回L;
    }


公共类CheckableLayout扩展的FrameLayout实现可检查{
    私人布尔mChecked;

    公共CheckableLayout(上下文的背景下){
        超(上下文);
    }

    公共无效setChecked(布尔检查){
        mChecked =检查;
        setBackgroundDrawable(检查?
                getResources()。getDrawable(R.drawable.blue)
                : 空值);
    }

    公共布尔器isChecked(){
        返回mChecked;
    }

    公共无效切换(){
        setChecked(!mChecked);
    }

}
 

我getView()code:

 公开查看getView(INT位置,查看convertView,ViewGroup中父){
    // TODO自动生成方法存根
    ViewHolder持有人;
    查看VI = convertView;

    如果(convertView == NULL){
        VI = inflater.inflate(com.egedsoft.instaprint.R.layout.item_clickable,NULL);
        持有人=新ViewHolder();
        holder.imgPhoto =(ImageView的)vi.findViewById(com.egedsoft.instaprint.R.id.imageClickable);
        vi.setTag(保持器);

    } 其他 {
        支架=(ViewHolder)vi.getTag();
    }


    如果(!arrayUrls.get(位置).getThumbnailUrl()。的isEmpty()){
        imageLoader.DisplayImage(arrayUrls.get(位置).getThumbnailUrl(),holder.imgPhoto);
    }


    返回六;
}
 

解决方案

这是我如何获取多张照片在我的活动。您可以使用它部件贴合你的逻辑。我用它来从相册中获取的Facebook图片。所以,我需要是(我假设),从您的需求不同。但同样,逻辑可能会使用你。

注意:这将是漫长的。 ; - )

这些都是全局声明的通过活动中使用:

  //存储网址,使API调用来
私人字符串URL;

//存储页面网址
私人字符串pagingURL;

//标志当前页面
INT current_page = 1;

//布尔检查,如果新的饲料加载
布尔loadingMore =真;

布尔stopLoadingData = FALSE;
 

这是获取初始设置图像的code座:

 私有类getPhotosData扩展的AsyncTask&LT;虚空,虚空,虚空&GT; {

    @覆盖
    保护无效doInBackground(虚空......为arg0){

        //改变加载更多状态,以preVENT重覆的来电FOR
        //更多数据而载入了一批
        loadingMore = TRUE;

        //设置初始网址GET专辑第一批
        URL =htt​​ps://graph.facebook.com/+ initialAlbumID
                +/相片和access_token =
                + Uti​​lity.mFacebook.getAccessToken()+?极限= 10;

        尝试 {

            HttpClient的HC =新DefaultHttpClient();
            HTTPGET GET =新HTTPGET(URL);
            HTT presponse RP = hc.execute(获得);

            如果(rp.getStatusLine()的getStatus code()== HttpStatus.SC_OK){
                串queryAlbums = EntityUtils.toString(rp.getEntity());

                JSONObject的JOTemp =新的JSONObject(queryAlbums);

                JSONArray JAPhotos = JOTemp.getJSONArray(数据);

                //在我的code,我得到下一个页面链接HERE

                getPhotos照片;

                的for(int i = 0; I&LT; JAPhotos.length();我++){
                    的JSONObject JOPhotos = JAPhotos.getJSONObject(ⅰ);
                    // Log.e(个人的相册,JOPhotos.toString());

                    如果(JOPhotos.has(链接)){

                        照片=新getPhotos();

                        //获取相册ID
                        如果(JOPhotos.has(ID)){
                            photos.setPhotoID(JOPhotos.getString(ID));
                        } 其他 {
                            photos.setPhotoID(空);
                        }

                        //获取专辑名称
                        如果(JOPhotos.has(名字)){
                            photos.setPhotoName(JOPhotos.getString(名字));
                        } 其他 {
                            photos.setPhotoName(空);
                        }

                        //获取专辑封面照片
                        如果(JOPhotos.has(图片报)){
                            photos.setPhotoPicture(JOPhotos
                                    .getString(图片报));
                        } 其他 {
                            photos.setPhotoPicture(空);
                        }

                        //获取照片的来源
                        如果(JOPhotos.has(源)){
                            photos.setPhotoSource(JOPhotos
                                    .getString(源));
                        } 其他 {
                            photos.setPhotoSource(空);
                        }

                        arrPhotos.add(照片);
                    }
                }
            }
        }赶上(例外五){
            e.printStackTrace();
        }

        返回null;
    }

    @覆盖
    保护无效onPostExecute(无效的结果){

        //设置适配器到GridView
        gridOfPhotos.setAdapter(适配器);

        //改变加载多个状态
        loadingMore = FALSE;
    }

}
 

这是检测当用户滚动到端并获取新图像组:

  // ONSCROLLLISTENER
gridOfPhotos.setOnScrollListener(新OnScrollListener(){

    @覆盖
    公共无效onScrollStateChanged(AbsListView观点,诠释scrollState){

    }

    @覆盖
    公共无效onScroll(AbsListView观点,诠释firstVisibleItem,
            INT visibleItemCount,诠释totalItemCount){
        INT lastInScreen = firstVisibleItem + visibleItemCount;
        如果((lastInScreen == totalItemCount)及&安培;!(loadingMore)){

            如果(stopLoadingData == FALSE){
                //取得饲料的下一批次
                新loadMorePhotos()执行();
            }

        }
    }
});
 

最后,我这是怎么获取下一组图片:

 私有类loadMorePhotos扩展的AsyncTask&LT;虚空,虚空,虚空&GT; {

    @覆盖
    保护无效doInBackground(虚空......为arg0){

        //设置加载更多真
        loadingMore = TRUE;

        //增加当前页面
        current_page + = 1;

        //下一个页面请求
        URL = pagingURL;

        尝试 {

            HttpClient的HC =新DefaultHttpClient();
            HTTPGET GET =新HTTPGET(URL);
            HTT presponse RP = hc.execute(获得);

            如果(rp.getStatusLine()的getStatus code()== HttpStatus.SC_OK){
                串queryAlbums = EntityUtils.toString(rp.getEntity());
                // Log.e(分页的结果,queryAlbums);

                JSONObject的JOTemp =新的JSONObject(queryAlbums);

                JSONArray JAPhotos = JOTemp.getJSONArray(数据);

                //在我的code,我得到下一个页面链接HERE

                getPhotos照片;

                的for(int i = 0; I&LT; JAPhotos.length();我++){
                    的JSONObject JOPhotos = JAPhotos.getJSONObject(ⅰ);
                    // Log.e(个人的相册,JOPhotos.toString());

                    如果(JOPhotos.has(链接)){

                        照片=新getPhotos();

                        //获取相册ID
                        如果(JOPhotos.has(ID)){
                            photos.setPhotoID(JOPhotos.getString(ID));
                        } 其他 {
                            photos.setPhotoID(空);
                        }

                        //获取专辑名称
                        如果(JOPhotos.has(名字)){
                            photos.setPhotoName(JOPhotos.getString(名字));
                        } 其他 {
                            photos.setPhotoName(空);
                        }

                        //获取专辑封面照片
                        如果(JOPhotos.has(图片报)){
                            photos.setPhotoPicture(JOPhotos
                                    .getString(图片报));
                        } 其他 {
                            photos.setPhotoPicture(空);
                        }

                        //获取专辑图片数
                        如果(JOPhotos.has(源)){
                            photos.setPhotoSource(JOPhotos
                                    .getString(源));
                        } 其他 {
                            photos.setPhotoSource(空);
                        }

                        arrPhotos.add(照片);
                    }
                }
            }
        }赶上(例外五){
            e.printStackTrace();
        }

        返回null;
    }

    @覆盖
    保护无效onPostExecute(无效的结果){

        //获取列表视图当前位置 - 用于保持滚动位置
        INT currentPosition = gridOfPhotos.getFirstVisiblePosition();

        //附加新数据到ArrayList并设置为适配器
        // 列表显示
        适配器=新PhotosAdapter(Photos.this,arrPhotos);
        gridOfPhotos.setAdapter(适配器);

        //设置新的滚动位置
        gridOfPhotos.setSelection(currentPosition + 1);

        //设置LOADINGMOREFALSE后增加新的馈送给现有
        // LIST
        loadingMore = FALSE;
    }

}
 

这是辅助类设置 GET 从查询收集上面的数据:

 公共类getPhotos {

    字符串PHOTOID;

    字符串PhotoName;

    字符串PhotoPicture;

    串光源;

    //设置照片的ID
    公共无效setPhotoID(字符串PHOTOID){
        this.PhotoID = PHOTOID;
    }

    //获取照片ID
    公共字符串getPhotoID(){
        返回PHOTOID;
    }

    //设置照片名称
    公共无效setPhotoName(字符串PhotoName){
        this.PhotoName = PhotoName;
    }

    //获取照片名称
    公共字符串getPhotoName(){
        返回PhotoName;
    }

    //设置照片么
    公共无效setPhotoPicture(字符串PhotoPicture){
        this.PhotoPicture = PhotoPicture;
    }

    //获取照片么
    公共字符串getPhotoPicture(){
        返回PhotoPicture;
    }

    //设置图片来源
    公共无效setPhotoSource(字符串光源){
        this.PhotoSource =光源;
    }

    //获取图片来源
    公共字符串getPhotoSource(){
        返回光源;
    }
}
 

如果您也想了适配器 code,让我知道。我使用费多尔的 延迟加载在适配器方法

唷。任何希望这有助于。如果你有进一步的问题,随时问。 : - )

编辑:适配器code补充说:

 公共类PhotosAdapter扩展了BaseAdapter {

    私人活动的活动;

    ArrayList的&LT; getPhotos&GT; arrayPhotos;

    私有静态LayoutInflater吹气= NULL;
    ImageLoader的ImageLoader的;

    公共PhotosAdapter(活动一,ArrayList的&LT; getPhotos&GT; arrPhotos){

        活性= A;

        arrayPhotos = arrPhotos;

        充气=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ImageLoader的=新ImageLoader的(activity.getApplicationContext());
    }

    公众诠释getCount将(){
        返回arrayPhotos.size();
    }

    公共对象的getItem(INT位置){
        返回arrayPhotos.get(位置);
    }

    众长getItemId(INT位置){
        返回的位置;
    }

    公共查看getView(最终诠释的立场,观点convertView,ViewGroup中父){

        ViewHolder持有人;

        查看VI = convertView;
        如果(convertView == NULL){
            VI = inflater.inflate(R.layout.photos_item,NULL);

            持有人=新ViewHolder();

            holder.imgPhoto =(ImageView的)vi.findViewById(R.id.grid_item_image);

            vi.setTag(保持器);
          } 其他 {
            支架=(ViewHolder)vi.getTag();
        }


        如果(arrayPhotos.get(位置).getPhotoPicture()!= NULL){
            imageLoader.DisplayImage(arrayPhotos.get(位置).getPhotoPicture(),holder.imgPhoto);
        }
        返回六;
    }

    静态类ViewHolder {
        ImageView的imgPhoto;

    }
}
 

编辑:添加的步骤,以显示进度,同时加载:

添加一个进度条到你的XML,你必须在GridView右侧下方。玩的重量,如果它会导致任何问题。

 &LT;的LinearLayout
    机器人:ID =@ + ID / linlaProgressBar
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =WRAP_CONTENT
    机器人:重力=中心
    机器人:方向=横向&GT;

    &LT;进度
        风格=@风格/微调
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:填充=2DP/&GT;
&LT; / LinearLayout中&GT;
 

在你的Java,声明的LinearLayout linlaProgressBar 作为全球然后将其丢在的onCreate()并设置它的能见度 linlaProgressBar.setVisibility(View.GONE);

而在在preExecute()使用这样的:

  @覆盖
在preExecute保护无效(){
    //显示底部的进度条(旋转)在装载更多的照片
    linlaProgressBar.setVisibility(View.VISIBLE);
}
 

和最后加,这在 onPostExecute()

  //隐藏底部的进度条(旋转)装载更多专辑后
linlaProgressBar.setVisibility(View.GONE);
 

In my application I need to download a lot of pictures from urls and display them in a gridView. (It can be between 1-200 pictures). I don't want to download all pictures at once. I read about lazy downloading and my question is: Can i get only one part of the Json, download the pictures in a different thread, and only if the user scroll down the gridView, I will continue to the other parts of the Json, and so on?

Edit: Hi again. I want to implement multi select in this gridView and i'm having difficulty to implement the code in the getView() method of the adapter. This is the example i'm using:example. How can I combine this code in my getView() method:

public View getView(int position, View convertView, ViewGroup parent) {
        CheckableLayout l;
        ImageView i;

        if (convertView == null) {
            i = new ImageView(Grid3.this);
            i.setScaleType(ImageView.ScaleType.FIT_CENTER);
            i.setLayoutParams(new ViewGroup.LayoutParams(50, 50));
            l = new CheckableLayout(Grid3.this);
            l.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT,
                    GridView.LayoutParams.WRAP_CONTENT));
            l.addView(i);
        } else {
            l = (CheckableLayout) convertView;
            i = (ImageView) l.getChildAt(0);
        }

        ResolveInfo info = mApps.get(position);
        i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));

        return l;
    }


public class CheckableLayout extends FrameLayout implements Checkable {
    private boolean mChecked;

    public CheckableLayout(Context context) {
        super(context);
    }

    public void setChecked(boolean checked) {
        mChecked = checked;
        setBackgroundDrawable(checked ?
                getResources().getDrawable(R.drawable.blue)
                : null);
    }

    public boolean isChecked() {
        return mChecked;
    }

    public void toggle() {
        setChecked(!mChecked);
    }

}

my getView() code:

public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    ViewHolder holder;
    View vi = convertView;

    if(convertView == null) {
        vi = inflater.inflate(com.egedsoft.instaprint.R.layout.item_clickable, null);
        holder = new ViewHolder();
        holder.imgPhoto = (ImageView)vi.findViewById(com.egedsoft.instaprint.R.id.imageClickable);
        vi.setTag(holder);

    } else {
        holder = (ViewHolder) vi.getTag();
    }


    if (!arrayUrls.get(position).getThumbnailUrl().isEmpty()){
        imageLoader.DisplayImage(arrayUrls.get(position).getThumbnailUrl(), holder.imgPhoto);
    }


    return vi;
}

解决方案

This is how I fetch multiple photos in my activity. You can use parts of it for fit your logic. I use this to fetch Facebook Images from an Album. So my needs are (I am assuming) different from your needs. But again, the logic may be of use to you.

Note: This will be lengthy. ;-)

These are the global declarations for use through the ACtivity:

// HOLD THE URL TO MAKE THE API CALL TO
private String URL;

// STORE THE PAGING URL
private String pagingURL;

// FLAG FOR CURRENT PAGE
int current_page = 1;

// BOOLEAN TO CHECK IF NEW FEEDS ARE LOADING
Boolean loadingMore = true;

Boolean stopLoadingData = false;

This is the code block that fetches the initial set of Images:

private class getPhotosData extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... arg0) {

        // CHANGE THE LOADING MORE STATUS TO PREVENT DUPLICATE CALLS FOR
        // MORE DATA WHILE LOADING A BATCH
        loadingMore = true;

        // SET THE INITIAL URL TO GET THE FIRST LOT OF ALBUMS
        URL = "https://graph.facebook.com/" + initialAlbumID
                + "/photos&access_token="
                + Utility.mFacebook.getAccessToken() + "?limit=10";

        try {

            HttpClient hc = new DefaultHttpClient();
            HttpGet get = new HttpGet(URL);
            HttpResponse rp = hc.execute(get);

            if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String queryAlbums = EntityUtils.toString(rp.getEntity());

                JSONObject JOTemp = new JSONObject(queryAlbums);

                JSONArray JAPhotos = JOTemp.getJSONArray("data");

                // IN MY CODE, I GET THE NEXT PAGE LINK HERE

                getPhotos photos;

                for (int i = 0; i < JAPhotos.length(); i++) {
                    JSONObject JOPhotos = JAPhotos.getJSONObject(i);
                    // Log.e("INDIVIDUAL ALBUMS", JOPhotos.toString());

                    if (JOPhotos.has("link")) {

                        photos = new getPhotos();

                        // GET THE ALBUM ID
                        if (JOPhotos.has("id")) {
                            photos.setPhotoID(JOPhotos.getString("id"));
                        } else {
                            photos.setPhotoID(null);
                        }

                        // GET THE ALBUM NAME
                        if (JOPhotos.has("name")) {
                            photos.setPhotoName(JOPhotos.getString("name"));
                        } else {
                            photos.setPhotoName(null);
                        }

                        // GET THE ALBUM COVER PHOTO
                        if (JOPhotos.has("picture")) {
                            photos.setPhotoPicture(JOPhotos
                                    .getString("picture"));
                        } else {
                            photos.setPhotoPicture(null);
                        }

                        // GET THE PHOTO'S SOURCE
                        if (JOPhotos.has("source")) {
                            photos.setPhotoSource(JOPhotos
                                    .getString("source"));
                        } else {
                            photos.setPhotoSource(null);
                        }

                        arrPhotos.add(photos);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        // SET THE ADAPTER TO THE GRIDVIEW
        gridOfPhotos.setAdapter(adapter);

        // CHANGE THE LOADING MORE STATUS
        loadingMore = false;
    }

}

This is to detect when the user has scrolled to the end and fetch new set of images:

// ONSCROLLLISTENER
gridOfPhotos.setOnScrollListener(new OnScrollListener() {

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        int lastInScreen = firstVisibleItem + visibleItemCount;
        if ((lastInScreen == totalItemCount) && !(loadingMore)) {

            if (stopLoadingData == false) {
                // FETCH THE NEXT BATCH OF FEEDS
                new loadMorePhotos().execute();
            }

        }
    }
});

And finally, this is how I fetch the next set of images:

private class loadMorePhotos extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... arg0) {

        // SET LOADING MORE "TRUE"
        loadingMore = true;

        // INCREMENT CURRENT PAGE
        current_page += 1;

        // Next page request
        URL = pagingURL;

        try {

            HttpClient hc = new DefaultHttpClient();
            HttpGet get = new HttpGet(URL);
            HttpResponse rp = hc.execute(get);

            if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String queryAlbums = EntityUtils.toString(rp.getEntity());
                // Log.e("PAGED RESULT", queryAlbums);

                JSONObject JOTemp = new JSONObject(queryAlbums);

                JSONArray JAPhotos = JOTemp.getJSONArray("data");

                // IN MY CODE, I GET THE NEXT PAGE LINK HERE

                getPhotos photos;

                for (int i = 0; i < JAPhotos.length(); i++) {
                    JSONObject JOPhotos = JAPhotos.getJSONObject(i);
                    // Log.e("INDIVIDUAL ALBUMS", JOPhotos.toString());

                    if (JOPhotos.has("link")) {

                        photos = new getPhotos();

                        // GET THE ALBUM ID
                        if (JOPhotos.has("id")) {
                            photos.setPhotoID(JOPhotos.getString("id"));
                        } else {
                            photos.setPhotoID(null);
                        }

                        // GET THE ALBUM NAME
                        if (JOPhotos.has("name")) {
                            photos.setPhotoName(JOPhotos.getString("name"));
                        } else {
                            photos.setPhotoName(null);
                        }

                        // GET THE ALBUM COVER PHOTO
                        if (JOPhotos.has("picture")) {
                            photos.setPhotoPicture(JOPhotos
                                    .getString("picture"));
                        } else {
                            photos.setPhotoPicture(null);
                        }

                        // GET THE ALBUM'S PHOTO COUNT
                        if (JOPhotos.has("source")) {
                            photos.setPhotoSource(JOPhotos
                                    .getString("source"));
                        } else {
                            photos.setPhotoSource(null);
                        }

                        arrPhotos.add(photos);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        // get listview current position - used to maintain scroll position
        int currentPosition = gridOfPhotos.getFirstVisiblePosition();

        // APPEND NEW DATA TO THE ARRAYLIST AND SET THE ADAPTER TO THE
        // LISTVIEW
        adapter = new PhotosAdapter(Photos.this, arrPhotos);
        gridOfPhotos.setAdapter(adapter);

        // Setting new scroll position
        gridOfPhotos.setSelection(currentPosition + 1);

        // SET LOADINGMORE "FALSE" AFTER ADDING NEW FEEDS TO THE EXISTING
        // LIST
        loadingMore = false;
    }

}

And this is the helper class to SET and GET the data collected from the queries above:

public class getPhotos {

    String PhotoID;

    String PhotoName;

    String PhotoPicture;

    String PhotoSource;

    // SET THE PHOTO ID
    public void setPhotoID(String PhotoID)  {
        this.PhotoID = PhotoID;
    }

    // GET THE PHOTO ID
    public String getPhotoID()  {
        return PhotoID;
    }

    // SET THE PHOTO NAME
    public void setPhotoName(String PhotoName)  {
        this.PhotoName = PhotoName;
    }

    // GET THE PHOTO NAME
    public String getPhotoName()    {
        return PhotoName;
    }

    // SET THE PHOTO PICTURE
    public void setPhotoPicture(String PhotoPicture)    {
        this.PhotoPicture = PhotoPicture;
    }

    // GET THE PHOTO PICTURE
    public String getPhotoPicture() {
        return PhotoPicture;
    }

    // SET THE PHOTO SOURCE
    public void setPhotoSource(String PhotoSource)  {
        this.PhotoSource = PhotoSource;
    }

    // GET THE PHOTO SOURCE
    public String getPhotoSource()  {
        return PhotoSource;
    }
}

If you also want the adapter code, let me know. I use Fedor's Lazy Loading method in the adapter.

Phew. Hope any of this helps. If you have further question, feel free to ask. :-)

EDIT: Adapter code added:

public class PhotosAdapter extends BaseAdapter {

    private Activity activity;

    ArrayList<getPhotos> arrayPhotos;

    private static LayoutInflater inflater = null;
    ImageLoader imageLoader; 

    public PhotosAdapter(Activity a, ArrayList<getPhotos> arrPhotos) {

        activity = a;

        arrayPhotos = arrPhotos;

        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader = new ImageLoader(activity.getApplicationContext());
    }

    public int getCount() {
        return arrayPhotos.size();
    }

    public Object getItem(int position) {
        return arrayPhotos.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {

        ViewHolder holder;

        View vi = convertView;
        if(convertView == null) {
            vi = inflater.inflate(R.layout.photos_item, null);

            holder = new ViewHolder();

            holder.imgPhoto = (ImageView)vi.findViewById(R.id.grid_item_image);

            vi.setTag(holder);
          } else {
            holder = (ViewHolder) vi.getTag();
        }


        if (arrayPhotos.get(position).getPhotoPicture() != null){
            imageLoader.DisplayImage(arrayPhotos.get(position).getPhotoPicture(), holder.imgPhoto);
        }
        return vi;
    }

    static class ViewHolder {
        ImageView imgPhoto;

    }
}

EDIT: Added steps to show Progress while loading:

Add a ProgressBar to you XML where you have the GridView right below it. Play around with the weight if it causes any problems.

<LinearLayout
    android:id="@+id/linlaProgressBar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="horizontal" >

    <ProgressBar
        style="@style/Spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="2dp" />
</LinearLayout>

In your Java, declare the Linearlayout linlaProgressBar as Global and cast it in the onCreate() and set it's visibility as linlaProgressBar.setVisibility(View.GONE);

And in the onPreExecute() use it like this:

@Override
protected void onPreExecute() {
    // SHOW THE BOTTOM PROGRESS BAR (SPINNER) WHILE LOADING MORE PHOTOS
    linlaProgressBar.setVisibility(View.VISIBLE);
}

And finally add, this in the onPostExecute()

// HIDE THE BOTTOM PROGRESS BAR (SPINNER) AFTER LOADING MORE ALBUMS
linlaProgressBar.setVisibility(View.GONE);

这篇关于懒惰下载图片到GridView控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆