此处的getView
功能位于自定义类ArrayAdapter
中。
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Thing p = getItem(position);
Thing.ThingStatus thingStatus = p.getStatus();
int thingStatusIcon; // change to thingStatusResource
switch (thingStatus) {
case A:
thingStatusIcon = ICON_A;
break;
case B:
thingStatusIcon = ICON_B;
break;
default:
thingStatusIcon = ICON_C;
break;
}
// Check if an existing view is being reused, otherwise inflate the view
ThingRowHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ThingRowHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.thing_list_item, parent, false);
// put these on the top like the colors
viewHolder.thingIcon = (ImageView) convertView.findViewById(R.id.thing_icon);
viewHolder.thingId = (TextView) convertView.findViewById(R.id.thing_id_item);
viewHolder.thingStatus = (TextView) convertView.findViewById(R.id.thing_status_item);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ThingRowHolder) convertView.getTag();
}
viewHolder.thingId.setText(p.getLpId());
viewHolder.thingStatus.setText(thingStatus.toString());
viewHolder.thingIcon.setImageResource(thingStatusIcon);
viewHolder.position = position;
return convertView;
}
我尝试为onClick
中的每一行添加ListView
事件监听器。我尝试在convertView
语句内部和if
语句之外的else
上设置侦听器。我的结果好坏参半。有时onClick
根本不会发射。其他时候会报告错误的立场。我已经搜索了SO的例子,我很惊讶这样一个共同的功能没有很好地记录和/或不适合我的情况。
非常感谢任何帮助!
编辑:
private class ThingRowHolder {
ImageView thingIcon;
TextView thingId;
TextView thingStatus;
}
编辑2:
private void refreshList() {
ArrayList<Thing> things = mThingContainer.getThings();
Collections.sort(things);
mThingListAdapter.refreshThings(things);
}
编辑3:
mThingListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ThingListAdapter.ThingRowHolder holder =
(ThingListAdapter.ThingRowHolder) view.getTag();
Thing p = mThingContainer.getThings().get(holder.position);
}
});
答案 0 :(得分:0)
在getView方法中使用这些
如果您需要长时间点击
convertView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {}}
如果您想要正常点击
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {}}
答案 1 :(得分:0)
将位置设置为视图的标记,
convertview.setTag(R.id.thing_icon, position);
现在在onClick(View v)
,
int pos = (int)v.getTag(R.id.thing_icon);
Thing p = getItem(pos);
您现在可以根据需要使用p。
编辑1:更新适配器中的数据
在适配器中,添加以下方法:
public void updateData(List<Thing> data) {
if (data != null) {
mData.clear();
mData.addAll(data);
notifyDataSetChanged();
}
}
现在只需在需要更新数据时调用适配器的updateData方法。