【问题标题】:How to Refresh listview with custom adapter如何使用自定义适配器刷新列表视图
【发布时间】:2015-07-06 03:08:36
【问题描述】:

从数据库中删除数据后,我需要很少的解决方案来刷新列表视图。我意识到我可以使用这个活动功能从数据库中删除数据:

helper.delete(String.valueOf(editID));
adapter.notifyDataSetChanged();
break;

在我的 DBHelper 中:

public void delete(String id) {
    String[] args = {id};
    getWritableDatabase().delete(TABLE_NAME, "_ID=?", args);
    getWritableDatabase().close();

此代码适用于删除数据库和项目,adapter.notifyDataSetChanged(); 但是当我关闭应用程序然后再次打开它时,listView 只会刷新。我需要一种如何立即刷新 listView 的方法。有些人使用adapter.remove(position);,立即刷新,然后调用.notifyDataSetChanged();。但它不适用于我的自定义适配器。

我用过这种适配器:

class ListAdapter extends CursorAdapter{
    @SuppressWarnings("deprecation")
    ListAdapter(Cursor c){
        super(MainActivity.this, c);
    }

    @Override
    public void bindView(View row, Context ctxt, Cursor c) {
        // TODO Auto-generated method stub
        ListHolder holder = (ListHolder)row.getTag();
        holder.populateFrom(c, helper);         
    }

    @Override
    public View newView(Context ctxt, Cursor c, ViewGroup parent) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = getLayoutInflater();
        View row = inflater.inflate(R.layout.custom_listview, parent, false);
        ListHolder holder = new ListHolder(row);
        row.setTag(holder);
        return (row);
    }       
}

static class ListHolder {
    private TextView nama = null, kategori=null;
    private ImageView icon=null;
    private View row = null;

    ListHolder(View row){
        this.row=row;

        nama=(TextView)row.findViewById(R.id.main_title_name);
        kategori=(TextView)row.findViewById(R.id.sub_title_name);
        icon=(ImageView)row.findViewById(R.id.thumbnail);
    }

    void populateFrom(Cursor c, DBHelper helper){
        nama.setText(helper.getNamaLok(c));
        kategori.setText(helper.getKatgLok(c));

        byte[] byteArray = helper.getImglok(c);
        Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0 ,byteArray.length);
        icon.setImageBitmap(bm);

    }               
}

对不起,我的英语不好,而且.. 希望有办法解决这个问题。在此先感谢。

【问题讨论】:

    标签: android listview custom-adapter


    【解决方案1】:

    您需要正确使用.notifyDataSetChanged();。 请记住,.notifyDataSetChanged() 方法使用适配器表示 数据已更改,您需要刷新

    通知附加的观察者底层数据已更改,任何反映数据集的视图都应自行刷新。

    所以您需要做的就是更改数据集,然后将notify 更改为适配器。 使用CussorAdapter,数据集是cursor,因此您应该按照以下方式更改光标:

    1. requery() 更新光标
    2. 使用changeCursor(Cursor cursor) 更改为新光标。

    也许this Link 会对你有所帮助。

    【讨论】:

    • 对于我的 CursorAdapter 案例,我必须在哪里初始化 requery()?在 bindView 或 newView 中,还是在按钮功能中删除?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多