在ListView中更改ImageView

时间:2012-08-06 09:43:01

标签: android listview imageview

我看到Android Hive的代码,我学会了如何将PHP脚本中的数组JSON发送到我的Android / Java代码。我成功地从在线数据库中检索了所有细节,并以我想要的格式显示它们。

问题是,我不知道在ListView中设置图像的src时很热。 这是我的代码。

                ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
                JSONParser jParser = new JSONParser();
                JSONObject json = jParser.getJSONFromUrl("http://domain.com/directory/database/retrieveComments.php?placeId=" + stringPlaceId);
                try
                {
                    commentsRatingsArray = json.getJSONArray("commentsRatings");
                    for(int i = 0; i < commentsRatingsArray.length(); i++)
                    {
                        JSONObject jsonObject = commentsRatingsArray.getJSONObject(i);
                        String dbUserFullName = jsonObject.getString(TAG_FULLNAME);
                        String dbUserEmail = jsonObject.getString(TAG_EMAIL);
                        String dbComment = jsonObject.getString(TAG_COMMENT);
                        String dbRating = jsonObject.getString(TAG_RATING);
                        String dbDate = jsonObject.getString(TAG_DATE);
                        String dbTime = jsonObject.getString(TAG_TIME);

                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put(TAG_FULLNAME, dbUserFullName);
                        map.put(TAG_EMAIL, dbUserEmail);
                        map.put(TAG_COMMENT, dbComment);
                        map.put(TAG_RATING, dbRating);
                        map.put(TAG_DATE, dbDate);
                        map.put(TAG_TIME, dbTime);

                        list.add(map);
                    }   
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    Toast.makeText(getBaseContext(), "Connection to the server is lost. Please check your internet connection.", Toast.LENGTH_SHORT).show();
                }

                ListAdapter adapter = new SimpleAdapter
                        (DisplayCommentsRatings.this, list, R.layout.commentrating,

                            new String[] { TAG_FULLNAME, TAG_EMAIL, TAG_COMMENT, TAG_DATE,  TAG_TIME },
                            new int[] {R.id.tvUserFullName, R.id.tvUserEmail, R.id.tvUserComment, R.id.tvDate, R.id.tvTime });

                setListAdapter(adapter);

请帮帮我,谢谢。

4 个答案:

答案 0 :(得分:5)

为此,我建议您为ListView定义自定义适配器

  1. 您可以通过扩展BaseAdapter或ArrayAdapter来创建自定义适配器类。
  2. 覆盖getView()方法。
  3. 在覆盖getView()方法时遵循ViewHolder模式。
  4. 在这里,拉维写了:Android custom ListView with Images and Text

    目前为止最好的解决方案:Andoid - Lazy Load of Images in ListView

答案 1 :(得分:0)

我认为您必须制作自己的自定义适配器(扩展BaseAdapter)并更新getView方法中的图像。 Google上有很多内容。

祝你好运=)

答案 2 :(得分:0)

例如,您可以使用指向文件SD名称的URL来设置图像。

http://developer.android.com/reference/android/widget/SimpleAdapter.html#setViewImage(android.widget.ImageView,int)

但我认为从BaseAdapter扩展并将你自己的Map或Array传递给它更容易,然后你可以使用你想要的任何图像充气,下载并设置它等等。

这是一个设备适配器的示例:)您不需要以viewHolder模式开始。

public class DevicesAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Device> devices;

public DevicesAdapter(Context context, List<Device> devices) {
    inflater = LayoutInflater.from(context);
    this.devices = devices;
}

@Override
public int getCount() {
    return devices.size();
}

@Override
public Object getItem(int position) {
    return devices.get(position);
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    if (row == null) {
        row = inflater.inflate(R.layout.account_devices_row, null);
    }
    TextView description = (TextView) row.findViewById(R.id.device_text);
    description.setText(devices.get(position).getLabel());
    return row;
}

}

此致

答案 3 :(得分:0)

他们在上面是正确的。您将需要扩展BaseAdapter并覆盖getView方法。您还希望延迟加载图像,因为您将下载它们,并且在执行此操作时不应占用UI线程。下面是我的Lazy Load类。简单地创建一个新类(我称之为LazyLoadImage.java)并将此代码粘贴在其中。以下是您可以使用该课程的不同方法:

使用placeHolder延迟加载图片:

new LazyLoadImage(ImageView imageView, String urlString, Bitmap placeHolder);

在没有placeHolder的情况下延迟加载图片:

new LazyLoadImage(ImageView imageView, String urlString);

手动清除缓存:

new LazyLoadImage().clearCache();

如果您的目标操作系统低于12,则需要在项目中包含“android-support-v4.jar”。

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.widget.ImageView;

public class LazyLoadImage extends AsyncTask<String, Void, Bitmap> {

ImageView mDestination;

//Set up cache size and cache
private static int mCacheSize = 4 * 1024 * 1024; // 4 mb
private static LruCache<String, Bitmap> mCache = new LruCache<String, Bitmap>(mCacheSize) {
    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight();
    }
};


public LazyLoadImage(ImageView destination, String urlString) {
    mDestination = destination;

    if (mCache.get(urlString) != null) {
        mDestination.setImageBitmap(mCache.get(urlString));
    }else {
        this.execute(urlString);
    }
}

public LazyLoadImage(ImageView destination, String urlString, Bitmap placeHolder) {
    mDestination = destination;

    if (mCache.get(urlString) != null) {
        mDestination.setImageBitmap(mCache.get(urlString));
    }else {
        setPlaceHolder(urlString, placeHolder);
        this.execute(urlString);
    }
}

public LazyLoadImage() {
}

private void setPlaceHolder(String urlString, Bitmap placeholder) {
    mDestination.setImageBitmap(placeholder);
}

public void clearCache() {
    mCache.evictAll();
}

@Override
protected Bitmap doInBackground(String... arg0) {

    //If the URI that is passed in arg0[0] is already in mCache then I return it without downloading it again
    if (mCache.get(arg0[0]) != null) {
        return mCache.get(arg0[0]);
    }else {

        Bitmap lazyImage = null;
        URL myFileUrl = null;          

        try {
             myFileUrl= new URL(arg0[0]);
             HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
             conn.setDoInput(true);
             conn.connect();
             InputStream is = conn.getInputStream();

             lazyImage = BitmapFactory.decodeStream(is);

             //Store the image in mCache for quick assess from anywhere in app
             synchronized (mCache) {
                if (mCache.get(arg0[0]) == null) {
                    mCache.put(arg0[0], lazyImage);
                }
             }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return lazyImage;
    }
}

@Override
protected void onCancelled(Bitmap result) {

}

@Override
protected void onPostExecute(Bitmap result) {

    /*
     * The returned image to the ImageView that was passed in on create
     *  (either from mCache or when downloaded the first time)
     */
    mDestination.setImageBitmap(result);

    super.onPostExecute(result);
}

}