在ListView中显示来自互联网的图像

时间:2014-12-30 18:16:48

标签: android listview

我希望这200张图片位于ListView的每一行。 我必须在CustomAdapter中复制从互联网上收集图片的代码吗?

    for(int i = 1; i <= 200; i++){
    final int ii = i;
    final ImageView imageView = new ImageView(CustomListView.this);
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
    //linearLayout.addView(imageView,lp);

    Thread thread = new Thread(){
        @Override
        public void run(){
            final Bitmap bm = getBitmapFromURL("http://ruthe.de/cartoons/strip_"+getPictureName(ii)+".jpg");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(bm !=null){
                        imageView.setImageBitmap(bm);
                    }
                    else {
                        //linearLayout.removeView(imageView);
                    }
                }
            });
        }
    };thread.start ();
}

这是我的CustomAdapter:

public class CustomAdapter extends BaseAdapter   implements View.OnClickListener {
    /*********** Declare Used Variables *********/
    private Activity activity;
private ArrayList data;
private static LayoutInflater inflater=null;
public Resources res;
ListModel tempValues=null;
int i=0;

/*************  CustomAdapter Constructor *****************/
public CustomAdapter(Activity a, ArrayList d,Resources resLocal) {

    /********** Take passed values **********/
    activity = a;
    data=d;
    res = resLocal;

    /***********  Layout inflator to call external xml layout () ***********/
    inflater = ( LayoutInflater )activity.
            getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
    if(data.size()<=0)
        return 1;
    return data.size();
}

public Object getItem(int position) {
    return position;
}

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

/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder{
    public TextView text;
    public TextView text1;
    public TextView textWide;
    public ImageView image;
}

/****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent) {

    View vi = convertView;
    ViewHolder holder;

    if(convertView==null){
        /****** Inflate tabitem.xml file for each row ( Defined below ) *******/
        vi = inflater.inflate(R.layout.tabitem, null);

        /****** View Holder Object to contain tabitem.xml file elements ******/
        holder = new ViewHolder();
        holder.text = (TextView) vi.findViewById(R.id.text);
        holder.text1=(TextView)vi.findViewById(R.id.text1);
        holder.image=(ImageView)vi.findViewById(R.id.image);
        /************  Set holder with LayoutInflater ************/
        vi.setTag( holder );
    }
    else
        holder=(ViewHolder)vi.getTag();

    if(data.size()<=0)
    {
        holder.text.setText("No Data");
    }
    else
    {
        /***** Get each Model object from Arraylist ********/
        tempValues=null;
        tempValues = ( ListModel ) data.get(position);
        /************  Set Model values in Holder elements ***********/
        holder.text.setText(tempValues.getCompanyName());
        holder.text1.setText( tempValues.getUrl() );
        holder.image.setImageResource(
                res.getIdentifier(
                        "com.androidexample.customlistview:drawable/"+tempValues.getImage(),null,null));
        /******** Set Item Click Listner for LayoutInflater for each row *******/
        vi.setOnClickListener(new OnItemClickListener( position ));
    }
    return vi;
}

@Override
public void onClick(View v) {
    Log.v("CustomAdapter", "=====Row button clicked=====");
}

/********* Called when Item click in ListView ************/
private class OnItemClickListener  implements View.OnClickListener{
    private int mPosition;

    OnItemClickListener(int position){
        mPosition = position;
    }
    @Override
    public void onClick(View arg0) {


        CustomListView sct = (CustomListView)activity;

        /****  Call  onItemClick Method inside CustomListViewAndroidExample Class ( See Below )****/

        sct.onItemClick(mPosition);
    }
}


//My own code
public static Bitmap getBitmapFromURL(String src) {
    try {URL url = new URL(src);
        return BitmapFactory.decodeStream(url.openConnection().getInputStream());
    }
    catch(Exception e){
        e.printStackTrace();
    }
    return null;
} //PICTURE BITMAP

public String getPictureName (int i){
    String in = ""+i+"";
    if(in.length() == 1){
        return "000"+in;
    }
    else if(in.length() == 2){
        return "00"+in;
    }
    else if(in.length() == 3){
        return "0"+in;
    }
    else{
        return in;
    }
}

我在整个互联网上搜索但是我没有找到解释如何从互联网上获取图片到ListView的每一行的东西......

4 个答案:

答案 0 :(得分:2)

PICASsO 允许在您的应用程序中轻松加载图像 - 通常只需一行代码! 图书馆检查此链接http://square.github.io/picasso/  在页面底部,您可以下载jar文件并将其粘贴到 libs 文件夹

Picasso.with(context).load("YOUR IMAGE URL").into(imageView);

你的getView方法

就像

一样
holder.image=(ImageView)vi.findViewById(R.id.image);

然后

Picasso.with(context).load("YOUR IMAGE URL").into(holder.image);

答案 1 :(得分:0)

看看毕加索图书馆。这非常容易。
http://square.github.io/picasso/

要使用它,只需使用标准findViewById找到您的ImageView,然后使用以下代码:

Picasso.with(context).load("www.google.com/images/1").into(imageView);

只需输入网址和ImageView,Picasso就会异步加载图片并将其放入图片视图中。

我正在使用它来显示列表视图中超过400个图像的列表,效果很好。

答案 2 :(得分:0)

除了线程之外,您可以使用适配器本身内的位图对象并使用位图对象初始化图像视图,使用位置整数而不是(ii)。

答案 3 :(得分:0)

您好我为我的应用找到了一种解决方法:我创建了一个类类型:

public class myClass {
....
...
private Bitmap imguser;

..并且在costructor中我添加了像Future这样的异步任务的对象,我发送了图像名称 从服务器端收到....

public myClass(..., ..,..,String userid, ...){

    Future<Bitmap> futureimguser;
    ExecutorService executor = Executors.newCachedThreadPool(); 

    getImgFromSite getimguserfromsite = new getImgFromSite(userid,"imguser");

    futureico = executor.submit(geticofromsite);
    futureimguser = executor.submit(getimguserfromsite)


        .......


    this.imguser = futureimguser.get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        this.icopoi = futureico.get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    executor.shutdown();

接下来,我有一个像下面这样的方法,从我的网站加载图像。

private final class getImgFromSite implements  Callable<Bitmap>  {
    String imgsrc = new String();
    String imgtipo = new String();
    public getImgFromSite(String srcimg,String imgtipo) {

        this.imgsrc = srcimg;
        this.imgtipo = imgtipo;
    }

    @Override
    public Bitmap call() throws Exception {
        String imgpath;
        if(imgtipo.compareTo("imguser") == 0){
            imgpath = "http://mysite/assets/imgcomics/"+imgsrc+".jpg";
        }
        else{
            imgpath = "http://mysite/"+imgsrc;

        }

        Bitmap myBitmap; 
        URL url = new URL(imgpath);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            myBitmap= BitmapFactory.decodeStream(input);
           return myBitmap;

    }

}

希望我能帮到你!