ListAdapter修改数据源(这是一个arraylist)

时间:2010-04-29 16:38:00

标签: java android listview listviewitem

这是我最近遇到的一个问题: 我有一个带有自定义适配器类的listview,适配器接受listview并使用它中的元素填充listview。现在,我想在列表视图的每一行上都有一个按钮来从中删除该项目。我该如何处理这个问题?有没有办法远程触发活动类中的方法并调用适配器上的notifydatachanged()方法来刷新列表视图?

2 个答案:

答案 0 :(得分: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;
}

}

答案 1 :(得分: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。这种技术为您提供了一种灵活的方式来修改适配器的任何方面,尽管这是相当有用的。