问题描述
- 点击按钮从 ListView中 删除一行
-
程序中的 ListView 的行包含一些 textviews 和一个按钮。当用户点击按钮时,我想删除父类
并把按钮从 ListView中 删除。如何在一个嵌套的方法(onClickListener)中访问自定义的 ArrayAdapter 的字段?我使用的是 View v。我是否要多次调用 v.getParent(),或者还有什么更好的方法?@Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; Action item = this.getItem(position); if (convertView == null) { convertView = inflater.inflate(R.layout.action_holder_layout, parent, false); holder = new ViewHolder(); holder.title = (TextView) convertView .findViewById(R.id.action_holder_title); holder.finishBtn = (Button) convertView .findViewById(R.id.finish_action_button); convertView.setTag(holder); } else holder = (ViewHolder) convertView.getTag(); holder.title.setText(item.getActionName()); holder.finishBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //REMOVE THE ACTION FROM THE ADAPTER'S ARRAYLIST } }); return convertView; } static class ViewHolder { private TextView title; private Button finishBtn; }
解决方案
@Override
public int getCount(){
return null!=list?list.size():0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Action item = this.getItem(position);
if (convertView == null) {
convertView = inflater.inflate(R.layout.action_holder_layout,
parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView
.findViewById(R.id.action_holder_title);
holder.finishBtn = (Button) convertView
.findViewById(R.id.finish_action_button);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.title.setText(item.getActionName());
holder.finishBtn.setTag(position);
holder.finishBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//REMOVE THE ACTION FROM THE ADAPTER'S ARRAYLIST
Object tag = v.getTag();
if(null!=tag){
list.remove((Integer)tag);
notifyDataSetChanged();
}
}
});
return convertView;
}
static class ViewHolder {
private TextView title;
private Button finishBtn;
}
解决方案二:
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
...
holder.finishBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
remove(position);
}
});
...
}
public void remove(int index) {
// list.remove(index);
...
notifyDataSetChanged();
}
时间: 2024-12-05 16:47:52