gpt4 book ai didi

安卓 ListView : how to notify datasource when delete one row?

转载 作者:行者123 更新时间:2023-11-30 03:05:36 24 4
gpt4 key购买 nike

我在每一行添加了一张删除图片,所以当点击图片删除这一行时,MyDapater的代码如下:

public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();

if (convertView == null) {
view = inflater.inflate(R.layout.row, null);
ItemViewHolder holder = new ItemViewHolder();
...
holder.deleteImage = (ImageView) view.findViewById(R.id.delete_icon);

holder.deleteImage.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
int pos = (Integer)v.getTag();
_list.remove(pos); // _list is a List storage the data
notifyDataSetChanged();
}

});

view.setTag(holder);
} else {
view = convertView;
}
ItemViewHolder holder = (ItemViewHolder) view.getTag();
holder.deleteImage.setTag(Integer.valueOf(position));

return view;
}

在 Activity 中,我的数据存储了一个 List 和以下代码:

adapter = new MyAdapter(this, _list);//
listView.setAdapter(adapter);

所以,当点击 delete-image 时,这一行就会消失。我的问题是:activity 如何知道删除哪一行?

最佳答案

简而言之,它不是。

如果您想让 Activity 知道删除了哪一行,您需要告诉它。我的首选方法是接口(interface)。

public interface DeleteListener{
public void rowDeleted(int pos);
}

并且 Activity 应该实现它

public class myActivity extends Activity implements DeleteListener{

创建适配器时传递 Activity 引用

adapter = new MyAdapter(this, _list, this);

并在适配器中触发删除事件

public MyAdapter(Context context, List _list, DeleteListener dListener){
//save the listener to a field
}
...
@Override
public void onClick(View v) {
int pos = (Integer)v.getTag();
_list.remove(pos); // _list is a List storage the data
dListener.rowDeleted(pos);
notifyDataSetChanged();
}

关于安卓 ListView : how to notify datasource when delete one row?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21876987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com