单击时将ListView更新为删除项目

时间:2013-05-21 05:27:05

标签: android listview adapter

我正在使用带有ListView的CursorAdapter和从sqlite数据库获取数据的游标。我有一个名为RenderList()的函数,我每次使用列表的新项更新数据库时调用,或者如果我将行的选中值设置为1(这将添加新项或strikethough项名)。

private void renderList(){

    String showWhere = show_checked ? null : DbHelper.C_CHECKED + "= '0' ";

    try {

        db = dbHelper.getReadableDatabase();
        cursor = db.query(DbHelper.TABLE, null, showWhere, null, null, null, dbHelper.C_ID + " DESC");

        groceriesList = (ListView)findViewById(R.id.listView1);
        adapter = new GroceryAdapter(this, cursor);
        adapter.newView(getApplicationContext(), cursor, groceriesList);            
        groceriesList.setAdapter(adapter);      
        groceriesList.setOnItemClickListener(itemListener);

     } catch (Exception e) {
         Log.d(TAG, "RenderList Error: ",e);
     }
}

这将重置列表,因此如果我单击列表视图中的项目,它会将列表视图重置为顶部位置。显然我错过了如何以高效,可用的方式更新列表视图和数据库的内容?

public class GroceryAdapter extends CursorAdapter {

    private final LayoutInflater mInflater;

    public GroceryAdapter(Context context, Cursor cursor) {

      super(context, cursor, true);
      mInflater = LayoutInflater.from(context);
     // mContext = context;

    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TwoLineListItem listItem = (TwoLineListItem)view;
        TextView t1 = listItem.getText1();
        TextView t2 = listItem.getText2();

        t1.setText(cursor.getString(cursor.getColumnIndex(DbHelper.C_GROCERY)));
        t2.setText("Added by: Wes");

        t1.setTag(cursor.getInt(cursor.getColumnIndex(DbHelper.C_ID)));
        t2.setTag(cursor.getInt(cursor.getColumnIndex(DbHelper.C_CHECKED)));

        if (cursor.getInt(cursor.getColumnIndex(DbHelper.C_CHECKED)) == 1 ) {
            t1.setPaintFlags(t1.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            listItem.setBackgroundColor(0xEECCCCCC);
        } else {
            t1.setPaintFlags(t1.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG) );
            listItem.setBackgroundColor(0x00000000);
        }
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        final View view = mInflater.inflate(R.layout.grocery_list_item, parent, false);
        return view;
    }

}

0 个答案:

没有答案