Android列表活动,在Android中动态加载来自网络的图像

时间:2010-11-18 12:23:33

标签: android

我描述了我的项目

在我的项目中在第一部分中,我已经解析了来自My web service的视频类别和图像URL链接的xml数据。我已经解析了这些数据并在我的主要活动中的ArrayList中接收了这些数据。 ArrayList是视频类别列表,第二个ArrayList是视频图片网址列表,我必须在{{1}中将ArrayList图片网址显示为ImageView我不知道,请给我一些解决方案。

1 个答案:

答案 0 :(得分:1)

为了处理除ListView中显示为TextView的String数组以外的其他内容,您需要编写自己的自定义适配器(因此Android知道如何显示这些项目)

以下是一个例子:

您的活动:

public class MyActivity extends Activity{
    private ArrayList<URL> MY_DATA;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Sets the View of the Activity
        setContentView(R.layout.my_activity);
        ListView myList = (ListView) findViewById(R.id.myList);
        MyAdapter adapter = new MyAdapter(this, MY_DATA);
        listView.setAdapter(adapter);
}

您的活动布局(此处为my_activity.xml):

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myList"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
/>

您的自定义适配器:

public class MyAdapter extends BaseAdapter{
    private LayoutInflater inflater;
    private ArrayList<URL> data;

    public EventAdapter(Context context, ArrayList<URL> data){
    // Caches the LayoutInflater for quicker use
    this.inflater = LayoutInflater.from(context);
    // Sets the events data
    this.data= data;
    }

    public int getCount() {
        return this.data.size();
    }

    public URL getItem(int position) throws IndexOutOfBoundsException{
        return this.data.get(position);
    }

    public long getItemId(int position) throws IndexOutOfBoundsException{
        if(position < getCount() && position >= 0 ){
            return position;
        }
    }

    public int getViewTypeCount(){
        return 1;
    }

    public View getView(int position, View convertView, ViewGroup parent){
        URL myUrl = getItem(position);
        ViewHolder holder = new ViewHolder(); // Use a ViewHolder to save your ImageView, in order not to have to do an expensive findViewById for each iteration

        // DO WHAT YOU WANT WITH YOUR URL (Start a new activity to download image?)

        if(convertView == null){ // If the View is not cached
        // Inflates the Common View from XML file
        convertView = this.inflater.inflate(R.id.my_row_layout, null);
            holder.myImageView = (ImageView)findViewById(R.id.myRowImageView);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        holder.myImageView.setImageBitmap(MY_BITMAP_I_JUST_DOWNLOADED);

        return convertView;
    }

    static class ViewHolder{
    ImageView myImageView;
    }
}

最后你的行的布局(my_row_layout.xml):

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myRowImageView"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>