我有一个带有按钮的CustomBase适配器,当我点击按钮时要删除该行,这是完全正常的,但我的问题是,我的适配器中填充的数据是来自远程服务器,我希望在删除它之前获取适配器所包含的信息并将其提供给我的MainActivity,在我的情况下,我希望在删除视图之前获取标题并将其发送到服务器,告诉它要从存储中删除它,最大的问题是所有代码与按钮都在我的baseAdapter类中,我不知道我是否可以在删除行之前给我的MainActivity数据,我想不出一种方法来实现如果有人有想法请分享,下面是我的基本适配器。
public class CartAdapter extends BaseAdapter{
private ArrayList<ListItem> listData;
private LayoutInflater layoutInflater;
ViewHolder holder;
public CartAdapter(Context context, ArrayList<ListItem> listData) {
this.listData = listData;
notifyDataSetChanged();
layoutInflater = LayoutInflater.from(context);
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.singlecartitem, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.title);
final ImageButton delete = (ImageButton) convertView.findViewById(R.id.delete);
convertView.findViewById(R.id.postCommentBox);
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listData.remove(position);
notifyDataSetChanged();
}
});
convertView.setTag(holder);
delete.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ListItem newsItem = listData.get(position);
holder.title.setText(newsItem.getTitle());
return convertView;
}
static class ViewHolder {
TextView title;
int position;
}
}
答案 0 :(得分:0)
您使用的是ListFragment吗?如果你这样做,请检查 this出来了。
如果不这样做,请让您的活动实施界面,例如使用例如HandleDeletion
方法handleTitle(String title)
。在clickListener中,将上下文对象强制转换为HandleDeletion
并在其上调用方法handleTitle(String title)
。这就是所谓的回调。
[编辑] 例如:
public interface HandleDeletion {
handleTitle(String title);
}
public class MyActivity implements HandleDeletion {
...
handleTitle(String title) {
//do whatever you want
}
...
}
public class CartAdapter extends BaseAdapter{
...
private Context context;
public CartAdapter(Context context, ArrayList<ListItem> listData) {
this.listData = listData;
this.context = context;
notifyDataSetChanged();
layoutInflater = LayoutInflater.from(context);
}
public View getView(final int position, View convertView, ViewGroup parent) {
...
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((HandleDeletion)context).handleTitle(listData.get(position).getTitle());
listData.remove(position);
notifyDataSetChanged();
}
});
...
}
...
}