在CursorAdapter中获取ContentResolver

时间:2013-06-02 01:25:56

标签: android android-contentprovider android-cursoradapter

我最近开始自学Android开发。现在我正在制作一个显示方框列表的应用程序;单击一个框显示其内容。主列表中的每个行视图在框名称旁边都有一个“删除”图标。我的ListAdapter是CursorAdapter的子类。在bindView()的{​​{1}}方法中,我执行以下操作:

CursorAdapter

如您所见,我已使用应删除的框的ID标记每个ImageButton。我想在这里做的是:

@Override
public void bindView(View view, Context context, Cursor cursor) {
    TextView name = (TextView) view.findViewById(R.id.text_box_name);
    name.setText(cursor.getString(cursor
            .getColumnIndex(DatabaseContract.BoxEntry.NAME)));
    name.setFocusable(false);
    ImageButton delete = (ImageButton) view.findViewById(R.id.button_box_delete);
    delete.setFocusable(false);
    delete.setTag(cursor.getLong(0));
    delete.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            long id = ((Long) view.getTag());
        }
    });
}

此代码会告诉我的自定义getContentResolver().delete(uri...); 删除该框及其所有内容。显而易见的问题是,在ContentProvider的上下文中,我无法调用CursorAdapter。从getContextResolver内与ContentProvider对话的最佳方式是什么?提前谢谢!

1 个答案:

答案 0 :(得分:1)

Context包含getContentResolver()方法,因此您可以将bindView写为:

@Override
public void bindView(View view, final Context context, Cursor cursor) {
    TextView name = (TextView) view.findViewById(R.id.text_box_name);
    name.setText(cursor.getString(cursor
        .getColumnIndex(DatabaseContract.BoxEntry.NAME)));
    name.setFocusable(false);
    ImageButton delete = (ImageButton) view.findViewById(R.id.button_box_delete);
    delete.setFocusable(false);
    delete.setTag(cursor.getLong(0));
    delete.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            long id = ((Long) view.getTag());
            context.getContentResolver().delete(uri...);
        }
    });

}

请注意,context必须为final才能在匿名内部类中引用它。