您是说列表中的 onItemClicked 正在返回不正确的项目吗?
好吧,我将简要介绍一下我遇到的一些问题,以及它们是否听起来像其中任何一个。
- 实现 onClickListener 并检索在列表视图中单击的视图的 ID 无法正常工作。这对我来说似乎是零星的,但我总是不得不绕过该功能。
解决方案:实现 onListItemClickListener 为您提供点击的位置,因此它不太依赖 Id(例如:R.id.viewId)
- 列表视图不断更改数字和值,使其成为您认为单击后会出现的错误值
解决方案:将对象引用保存在封装的 BaseAdapter 类中。我对 Volley 没有太多经验,但从头开始需要扩展 BaseAdapter 的类,并且您可以扩充自己的视图并填充数据。
- 确保您设置了正确的数据以传递到您的 fetch 类中
这可能是 #1s 问题的结果,而且通常是这样,但如果您正在分配视图控件,请确保它们都有自己的唯一引用,并相对于膨胀的视图进行检索:
//Method inflates a view as part of an implementation of BaseAdapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LayoutInflaterService);
convertView = inflater.inflater(R.layout.MYVIEW, parent, false);
//Note the retrieval relative to the view being inflated
final TextView tvURL = (TextView)convertView.findViewById(R.id.tvURL);
tvURL.setText("www.stackoverflow.com");
tvURL.setOnClickListener(new View.OnClickListener()
fetchURL(tvURL.getText().toString());
return convertView;
}
编辑
一个示例适配器:
public class MyAdapter extends BaseAdapter {
private Context context = null;
private ArrayList<CustomItem> items = new ArrayList<>();
public MyAdapter(Context context, ArrayList<CustomItem> items)
{
this.context = context;
this.items = items;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
//will never exceed position as that has a range of 0 to the size we give
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.mylistitem);
TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
ImageView ivFeature = (ImageView)convertView.findViewById(R.id.ivFeature);
TextView tvDescription = (TextView)convertView.findViewById(R.id.tvDescription);
CustomItem item = items.get(position);
tvName.setText(item.getName());
tvDescription.setText(item.getDescription());
//Call for your item to process a picture into a bitmap then
ivFeature.setImageBitmap(item.getFeatureImage());
return convertView;
}
}
/*
//Instantiation:
myListView = (ListView)findViewById(R.id.myListView);
MyAdapter adapter = new MyAdapter(Activity.this, myItemsList);
myListView.setAdapter(adapter);
myListView.invalidate();
*/