草庐IT

android - 在 listView 中加载异步图片

coder 2023-11-22 原文

我想在 ListView 中加载数据后从服务器加载图像。 我知道这个问题存在很多主题,但我还没有找到解决方案...

所以这是我的代码:

//asyncTackClass for loadingpictures
public class LoadImagesThread extends AsyncTask<Bundle, Void, Bitmap> {
    private ImageView view;
    private Bitmap bm;
    private Context context;
    private final WeakReference<ImageView> imageViewReference;

    private final String BUNDLE_URL = "url";
    private final String BUNDLE_NAME = "name";
    private final String BUNDLE_BM = "bm";

    public LoadImagesThread(Context context, ImageView view) {
        this.context=context;
        imageViewReference = new WeakReference<ImageView>(view);
    }

    @Override
    protected Bitmap doInBackground(Bundle... b) {

        Bitmap bm =null;
        if (StorageHelper.getBitmap(b[0].getString(BUNDLE_NAME)) != null) { // Check the sdcard
            bm = StorageHelper.getBitmap(b[0].getString(BUNDLE_NAME));
            Log.w("LoadImagesThread", "Get image from sdcard : "+b[0].getString(BUNDLE_NAME));
        } else { // Check the server
            bm = ServiceHelper.getBitmapFromURL(b[0].getString(BUNDLE_URL));
            StorageHelper.saveBitmap(bm, b[0].getString(BUNDLE_NAME)); // Save image on sdcard   
            Log.w("LoadImagesThread", "Get image from server : "+b[0].getString(BUNDLE_NAME));
        }

        return bm;
    }

    @Override
    protected void onPostExecute(final Bitmap bm) {
        super.onPostExecute(bm);        
        if (bm != null){ //if bitmap exists...
            view = imageViewReference.get();
            // Fade out
            Animation fadeOutAnimation = AnimationUtils.loadAnimation(context, R.anim.fadeoutimage);
            fadeOutAnimation.setAnimationListener(new AnimationListener() {

            public void onAnimationStart(Animation animation) {

            }

            public void onAnimationRepeat(Animation animation) {

            }

            public void onAnimationEnd(Animation animation) {
                // Fade in
                view.setImageBitmap(bm);
                Animation fadeInAnimation = AnimationUtils.loadAnimation(context, R.anim.fadeinimage);
                view.startAnimation(fadeInAnimation);
            }
        });

            // Launch the fadeout
            view.startAnimation(fadeOutAnimation);


        }else{ //if not picture, display the default ressource
            view.setImageResource(R.drawable.productcarre);
        }

    }

}

代码用于在ImageView中显示Bitmap

这是适配器:

public class ListViewShoplistStoresAdapter extends BaseAdapter {

private ArrayList<Shop> shopList;
private Activity activity;

private HashMap<Integer, ImageView> views;
private final String BUNDLE_URL = "url";
private final String BUNDLE_NAME = "name";
private final String BUNDLE_POS = "pos";
private final String BUNDLE_ID = "id";


public ListViewShoplistStoresAdapter(Activity activity, ArrayList<Shop> shopList) {
    super();
    this.activity = activity;
    this.shopList = shopList;
    this.views = new HashMap<Integer, ImageView>();
}

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

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

public long getItemId(int position) {
    return shopList.get(position).getId();
}

private class ViewHolder {
    public TextView store;
    public TextView name;
    public ImageView ImageStore;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder view;
    LayoutInflater inflator = activity.getLayoutInflater();

    if(convertView == null) {
        view = new ViewHolder();
        convertView = inflator.inflate(R.layout.listviewshops, null);

        view.store = (TextView) convertView.findViewById(R.id.store);
        view.name = (TextView) convertView.findViewById(R.id.name);
        view.ImageStore = (ImageView) convertView.findViewById(R.id.imgstore);

        convertView.setTag(view);
    }else {
        view = (ViewHolder) convertView.getTag();
    }

    Typeface regular=Typeface.createFromAsset(activity.getAssets(), "fonts/RobotoRegular.ttf");
    view.store.setTypeface(regular);

    Typeface light=Typeface.createFromAsset(activity.getAssets(), "fonts/RobotoLight.ttf");
    view.store.setTypeface(light);
    Brand brand = StorageHelper.getBrand(activity, shopList.get(position).getBrandId());
    if (brand == null) {
        Log.e("SetShopInAdapter","Brand null");
        Toast.makeText(activity, "Impossible d'afficher la liste de magasins", Toast.LENGTH_LONG).show();
    } else {
        view.store.setText(brand.getName());
        view.name.setText(shopList.get(position).getName());
        view.ImageStore.setImageResource(R.drawable.productcarre);
    }

    Bundle b = new Bundle();

    //url of the pict
    b.putString(BUNDLE_URL, ServiceHelper.getImageUrl("brand", brand.getName()));

    // name of image
    b.putString(BUNDLE_NAME, ServiceHelper.getCleanImageName(brand.getName()));

    //position in the listView
    b.putInt(BUNDLE_POS, position);

    //id of the current object
    b.putInt(BUNDLE_ID, brand.getId());

    //put info in the map in order to display in the onPostExecute
    if(views.get(position)==null){
        views.put(position, view.ImageStore);
        // launch thread
        new LoadImagesThread(activity.getApplicationContext(), view.ImageStore).execute(b);
    }

    return convertView;

}

}

所以,当我使用 GridView 时,没有任何问题,但是当我使用 ListView 时,图像仅在第一个项目中发生变化!

示例: 我想显示“汽车”、“房子”和“苹果”商品的产品图片。 代码将启动线程,所有图像(汽车然后是房子,最后是苹果)将显示在第一个项目(汽车项目)中...... 房子和苹果虽然没有图像!!

你知道我该怎么做吗?

谢谢

最佳答案

SO 上有很多关于这个的内容.. 像这样的异步加载称为“延迟加载”

https://github.com/thest1/LazyList

用列表来完整实现这样一个过程

对于一般的加载图像,我推荐这个:

https://github.com/nostra13/Android-Universal-Image-Loader

关于android - 在 listView 中加载异步图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12933783/

有关android - 在 listView 中加载异步图片的更多相关文章

  1. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  2. ruby-on-rails - Ruby on Rails - 为文本区域和图片生成列 - 2

    我是Rails的新手,所以请原谅简单的问题。我正在为一家公司创建一个网站。那家公司想在网站上展示它的客户。我想让客户自己管理这个。我正在为“客户”生成一个表格,我想要的三列是:公司名称、公司描述和Logo。对于名称,我使用的是name:string但不确定如何在脚本/生成脚手架终端命令中最好地创建描述列(因为我打算将其设置为文本区域)和图片。我怀疑描述(我想成为一个文本区域)应该仍然是描述:字符串,然后以实际形式进行调整。不确定如何处理图片字段。那么……说来话长:我在脚手架命令中输入什么来生成描述和图片列? 最佳答案 对于“文本”数

  3. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  4. ruby-on-rails - 在 Ruby on Rails 中发送响应之前如何等待多个异步操作完成? - 2

    在我做的一些网络开发中,我有多个操作开始,比如对外部API的GET请求,我希望它们同时开始,因为一个不依赖另一个的结果。我希望事情能够在后台运行。我找到了concurrent-rubylibrary这似乎运作良好。通过将其混合到您创建的类中,该类的方法具有在后台线程上运行的异步版本。这导致我编写如下代码,其中FirstAsyncWorker和SecondAsyncWorker是我编写的类,我在其中混合了Concurrent::Async模块,并编写了一个名为“work”的方法来发送HTTP请求:defindexop1_result=FirstAsyncWorker.new.async.

  5. ruby-on-rails - Rails 3,在RAILS_ROOT上方显示来自本地文件系统的jpg图片 - 2

    我正在尝试找出一种方法来显示来自不在RAILS_ROOT下(在RedHat或Ubuntu环境中)的已安装文件系统的图像。我不想使用符号链接(symboliclink),因为这个应用程序实际上是通过Tomcat部署的,而当我关闭Tomcat时,Tomcat会尝试跟随符号链接(symboliclink)并删除挂载中的所有图像。由于这些文件的数量和大小,将图像放在public/images下也不是一种选择。我查看了send_file,但它只会显示一张图片。我需要在一个格式良好的页面中显示6个请求的图像。由于膨胀,我宁愿不使用Base64编码,但我不知道如何将图像数据与呈现的页面一起传递下去。

  6. 最新版人脸识别小程序 图片识别 生成二维码签到 地图上选点进行位置签到 计算签到距离 课程会议活动打卡日常考勤 上课签到打卡考勤口令签到 - 2

    技术选型1,前端小程序原生MINA框架cssJavaScriptWxml2,管理后台云开发Cms内容管理系统web网页3,数据后台小程序云开发云函数云开发数据库(基于MongoDB)云存储4,人脸识别算法基于百度智能云实现人脸识别一,用户端效果图预览老规矩我们先来看效果图,如果效果图符合你的需求,就继续往下看,如果不符合你的需求,可以跳过。1-1,登录注册页可以看到登录页有注册入口,注册页如下我们的注册,需要管理员审核,审核通过后才可以正常登录使用小程序1-2,个人中心页登录成功以后,我们会进入个人中心页我们在个人中心页可以注册人脸,因为我们做人脸识别签到,需要先注册人脸才可以进行人脸比对,进

  7. ruby - 使用什么异步 Ruby 服务器? - 2

    我们开始使用Ruby开发新游戏项目。我们决定使用其中一种异步Ruby服务器,但我们无法决定选择哪一种。选项是:歌利亚抽筋+消瘦/彩虹rack-fiber_pool+rack+thin/rainbowseventmachine_httpserver它们似乎都在处理HTTP请求。Cramp还支持开箱即用的Websocket和服务器端事件。您知道这些服务器的优缺点吗? 最佳答案 我使用eventmachine_httpserver公开了一个RESTfulAPIinanEventMachine-basedIRCbot绝对不会推荐它用于任何严

  8. Ruby 并发/异步处理(简单用例) - 2

    我一直在研究ruby​​的并行/异步处理能力,并阅读了许多文章和博客文章。我查看了EventMachine、Fibers、Revactor、Reia等。不幸的是,我无法为这个非常简单的用例找到简单、有效(且非IO阻塞)的解决方案:File.open('somelogfile.txt')do|file|whileline=file.gets#(R)ReadfromIOline=process_line(line)#(P)Processthelinewrite_to_db(line)#(W)WritetheoutputtosomeIO(DBorfile)endend你看到了吗,我的小脚本正

  9. ruby-on-rails - 带图片 uploader 的多步表单 - 2

    我想建立3步用户注册,在第2步上传头像。所以我遵循RyanBates的指南http://railscasts.com/episodes/217-multistep-forms.我正在使用CarrierWavegem来处理上传。但似乎我无法在用户session中存储上传的文件信息(我收到无法转储文件错误)。我在Controller中使用以下技术ifparams[:user][:img_path]@uploader=FirmImgUploader.new@uploader.store!(params[:user][:img_path])session[:img]=@uploaderpara

  10. ruby - 如何在 Ruby 中更新图片文件的 EXIF 标签? - 2

    标题说明一切。 最佳答案 我正在使用MiniExiftool,它是Perl的Exiftool的ruby​​接口(interface)。https://github.com/janfri/mini_exiftoolhttp://www.sno.phy.queensu.ca/~phil/exiftool/用法:exif=MiniExiftool.new(file_path)exif.date_time_original=Time.nowexif["captionextract"]="Thisismynewcaption"exif.sav

随机推荐