这是我最近遇到的一个问题:我有一个带有自定义适配器类的列表视图,适配器接收一个列表视图并用其中的元素填充列表视图。现在,我想在列表视图的每一行上都有一个按钮来从中删除项目。我应该如何解决这个问题?有没有办法远程触发activity类中的某个方法,调用适配器上的notifydatachanged()方法来刷新listview?
问问题
1590 次
2 回答
1
我做过这样的事情:
public class MyAdapter extends Adapter {
private final ArrayList<String> items = new ArrayList<String>();
// ...
deleteRow(int position) {
items.remove(position);
notifyDataSetChanged();
}
//
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
Tag tag = new Tag();
// inflate as usual, store references to widgets in the tag
tag.button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
deleteRow(position);
}
});
}
// don't forget to set the actual position for each row
Tag tag = (Tag)convertView.getTag();
// ...
tag.position = position;
// ...
}
class Tag {
int position;
TextView text1;
// ...
Button button;
}
}
于 2010-04-29T18:40:17.977 回答
0
在getView()方法中,不能只在按钮上setOnClickListener()吗?
像这样的东西:
static final class MyAdapter extends BaseAdapter {
/** override other methods here */
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
// inflate the view for row from xml file
// keep a reference to each widget on the row.
// here I only care about the button
holder = new ViewHolder();
holder.mButton = (Button)convertView.findViewById(R.id.button);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
// redefine the action for the button corresponding to the row
holder.mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// do something depending on position
performSomeAction(position);
// mark data as changed
MyAdapter.this.notifyDatasetChanged();
}
}
}
static final class ViewHolder {
// references to widgets
Button mButton;
}
}
如果您不确定是否要扩展 BaseAdapter,请查看 ApiDemos 中的示例 List14。这种技术为您提供了一种灵活的方式来修改适配器的几乎任何方面,尽管它是相当多的工作。
于 2010-04-29T16:55:22.100 回答