我有一堆资源图像,我想为ListView的每个元素显示一个。目前我有一个row.xml文件,每个元素都显示“icon”图像。我想使用我在row.xml中指定的相同格式,但是每次都将图像更改为我想要的格式。
我做过一些关于“延迟加载”的研究,但看起来它过于复杂,并不适用于此。
答案 0 :(得分:1)
答案 1 :(得分:1)
好的,要扩展上面的答案,你可以创建一个“适配器”,如下面的代码所示:
package com.example.consumer.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.consumer.R;
import com.example.consumer.model.AppModel;
import com.example.consumer.model.Deal;
public class DealListAdapter extends BaseAdapter {
private static ArrayList<Deal> dealArrayList = new ArrayList<Deal>();
private LayoutInflater inflator;
private AppModel appModel;
public DealListAdapter(Context context, ArrayList<Deal> results) {
dealArrayList = results;
inflator = LayoutInflater.from(context);
appModel = (AppModel) context.getApplicationContext();
}
public int getCount() {
if (dealArrayList == null)
return 0;
else
return dealArrayList.size();
}
public Object getItem(int position) {
try {
return dealArrayList.get(position);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflator.inflate(R.layout.list_item_deal, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.deal_listview_item_one);
holder.distance = (TextView) convertView.findViewById(R.id.deal_listview_item_two);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(dealArrayList.get(position).getMerchantName() + ": "+ dealArrayList.get(position).getTitle());
holder.distance.setText(dealArrayList.get(position).getDistanceFormatted(appModel.getLocation()));
return convertView;
}
static class ViewHolder {
TextView name;
TextView distance;
}
}
请注意使用ViewHolder - 这将节省大量“findViewById”调用。
要在列表中使用此适配器,请使用以下代码:
dealList = (ListView) findViewById(R.id.browse_list_view);
dealListAdapter = new DealListAdapter(this, dealList);
dealList.setAdapter(dealListAdapter);
在这种情况下,dealList
是Deals的数组列表(你会使用其他一些自定义对象)
希望这有助于您的OO编程...:)
答案 2 :(得分:0)
我找到了一个在listview,gridview中显示图像的有用示例。希望它对你非常有用。