listView滚动记忆

时间:2014-10-19 19:41:57

标签: android listview android-listview

我得到了这个listView,它是通过自定义游标适配器从SQL数据库中填充的。当我点击某个项目时,会出现一个对话框并要求确认删除该条目。如果我选择YES,它也会删除列表和SQL条目中的项目,并且我创建的setListView方法重新加载列表并滚动回列表的顶部。 我想要做的是,当我删除一个项目时,列表应该记住它的位置并显示那些已删除项目附近的项目(我不想让它回到列表的顶部)。我怎么能做到这一点?

这是我的代码(onItemClick和setListView方法):

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

    final long arg3mod = arg3;

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(HistoryActivityMod.this);

    // Setting Dialog Title
    alertDialog.setTitle("Confirm Delete...");

    // Setting Dialog Message
    alertDialog.setMessage("Are you sure you want delete this?");

    alertDialog.setIcon(android.R.drawable.ic_menu_delete);

    // Setting Positive "Yes" Button
    alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {

            db.delete(DbHelper.TABLE_NAME, DbHelper.C_ID+"="+arg3mod, null);
            setListView();

        Toast.makeText(getApplicationContext(), "Entry was deleted", Toast.LENGTH_SHORT).show();

        }
    });


    // Setting Negative "NO" Button
    alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

        Toast.makeText(getApplicationContext(), "Nothing changed", Toast.LENGTH_SHORT).show();
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();

}

public void setListView (){
    String[] columns= {DbHelper.C_ID, DbHelper.ROW1, DbHelper.ROW2, DbHelper.ROW3, DbHelper.ROW4, DbHelper.ROW5};

    Cursor cursor = db.query(DbHelper.TABLE_NAME, columns, null, null, null, null, "_id DESC");

    CustomCursorAdapter adapter = new CustomCursorAdapter(getApplicationContext(),cursor, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

    lv.setAdapter(adapter);

}

2 个答案:

答案 0 :(得分:1)

尝试以下方法:

public void setListView (){
    String[] columns= {DbHelper.C_ID, DbHelper.ROW1, DbHelper.ROW2, DbHelper.ROW3, DbHelper.ROW4, DbHelper.ROW5};

    Cursor cursor = db.query(DbHelper.TABLE_NAME, columns, null, null, null, null, "_id DESC");
    if(lv.getAdapter() == null) {
        CustomCursorAdapter adapter = new CustomCursorAdapter(getApplicationContext(),cursor, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        lv.setAdapter(adapter);
    } else {
        ((CustomCursorAdapter)lv.getAdapter()).changeCursor(cursor);
    }

}

答案 1 :(得分:0)

问题是您拨打lv.setAdapter(adapter),这会导致您的列表重置为顶部。您只能lv.setAdapter(adapter)一次,如果您的适配器是CursorAdapter,则可以使用其changeCursor(cursor)方法更新其下层数据。

因此,在setListView()方法中,您可以将lv.setAdapter(adapter)替换为adapter.changeCursor(cursor)

参考文献: https://developer.android.com/reference/android/widget/CursorAdapter.html#changeCursor(android.database.Cursor)

相关问题