自定义列表适配器类。
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, null);
holder = new ViewHolder();
holder.image = (ImageView) convertView.findViewById(R.id.item_image);
holder.name = (TextView) convertView.findViewById(R.id.item_name);
holder.price = (TextView) convertView.findViewById(R.id.item_price);
holder.qty = (Spinner) convertView.findViewById(R.id.spinner_qty);
holder.delete_btn = (Button) convertView.findViewById(R.id.delete_btn);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//holder.image
holder.name.setText(productArray.get(position).getName());
holder.price.setText("$"+ productArray.get(position).getPrice());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, quantity);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qty.setAdapter(adapter);
return convertView;
}
如何单击delete_btn以删除listview项。我不知道如何访问listview。请帮助!
答案 0 :(得分:0)
在getView()中添加:
holder.delete_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
yourlist.remove(position);
notifyDataSetChanged();
}
});
答案 1 :(得分:0)
实际上,您还需要选择项目位置来更改数据集(列表项)
所以您的getView();
将
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
.......
holder.delete_btn = (Button) convertView.findViewById(R.id.delete_btn);
holder.delete_btn.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
//selected item position
int itemPosition=(int)view.getTag();
//deletion stuff
productArray.remove(position);
notifyDataSetChanged();
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.delete_btn.setTag(position)//set item position
holder.name.setText(productArray.get(position).getName());
.......
return convertView;
}
已更新: 检查按钮onClick监听器方法。请参阅@Nikhil @nag