已更新:
我已经从FireStore和设置适配器下载了数据。然后在RecyclerView中显示数据。
我的问题是:如果我想通过单击RecyclerView外部的按钮删除RecyclerView中的任何项目,该怎么办?
步骤示例:
从Firestore获取数据(完成) example pic
单击“编辑”按钮,然后在每个项目中显示“删除图标按钮” example pic
单击“删除图标按钮”,然后将该项目删除。
布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F8F8F8">
<TextView
android:id="@+id/editBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:text="edit"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<RecyclerView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="16dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
</android.support.constraint.ConstraintLayout>
答案 0 :(得分:0)
从适配器中使用的列表中删除该项目。
然后调用NotifyDataSetChanged()
函数,适配器将从中显示更新的列表。
如果您还发布一些代码,则更容易进行后续指导。
答案 1 :(得分:0)
在您的onBindViewHolder中
holder.delete_button.setOnClickListener {
AlertDialog.Builder(context)
.setTitle("Are you sure?")
.setMessage("Are you sure you want to Delete this File ?")
.setPositiveButton("YES"
) { dialog, which ->
deleteDb(post_id, position);//Call your methode here
dialog.dismiss();
}
.setNegativeButton("NO") { dialog, which ->
dialog.dismiss()
}
.create()
.show()
}
public void deleteDb(String id,int position ) {
DbOperations dbOperations =new DbOperations(context);
SQLiteDatabase db = dbOperations.getWritableDatabase();
dbOperations.delete(db, id);
notifyItemRemoved(position);
audioItems.remove(position);
notifyItemRangeChanged(position, audioItems.size);//this will update your View
}
在您的DbOperation类中
public void delete(SQLiteDatabase db, String id) {
ContentValues contentValues = new ContentValues();
contentValues.put(ProductContract.ProductEntry.ID, id);
db.execSQL("DELETE FROM " + ProductContract.ProductEntry.TABLE_NAME + " WHERE "
+ ProductContract.ProductEntry.ID + "= '" + id + "'");
}
答案 2 :(得分:0)
在删除按钮上,单击以获取被单击的对象。请参阅示例代码
Contact contact=arraylist.get(getAdapterPosition());
deletecontact(contact);
这是从数据库中删除特定记录的方法
public void deletecontact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Note.TABLE_NAME, Note.COLUMN_ID + " = ?",
new String[]{String.valueOf(contact.getId())});
db.close();
}
答案 3 :(得分:0)
您需要创建接口并实现相同的方法。单击按钮时,您需要调用该方法并在您的适配器类中覆盖该方法,您可以在其中更改可见性或根据需要执行一些操作。