我有一个Recycler视图,其中包含存储在Firebase中的板(数据类),当我向左或向右滑动时,我想删除板,但我想不出一个方法来做到这一点,所以如果有人能告诉我如何做到这一点或任何建议都会有很大帮助,这将是非常有帮助的,谢谢。
我的回收适配器视图
open class BoardItemAdapter(private val context: Context, private val list: ArrayList<Board>): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var onClickListener: OnClickListener? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return MyViewHolder(LayoutInflater.from(context).inflate(R.layout.recyclerview_itemboard, parent, false))
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val model = list[position]
if(holder is MyViewHolder) {
Glide
.with(context)
.load(model.image)
.centerCrop()
.placeholder(R.drawable.ic_nav_user)
.into(holder.itemView.findViewById(R.id.ivboardimage))
holder.itemView.findViewById<TextView>(R.id.tvname).text = model.name
holder.itemView.findViewById<TextView>(R.id.tvcreatedby).text = "Created By: ${model.createdBy}"
holder.itemView.setOnClickListener {
if(onClickListener!=null) {
onClickListener!!.onClick(position,model)
}
}
}
}
override fun getItemCount(): Int {
return list.size
}
interface OnClickListener {
fun onClick(position: Int, model: Board)
}
fun setOnClickListener(onClickListener: OnClickListener) {
this.onClickListener = onClickListener
}
private class MyViewHolder(view: View): RecyclerView.ViewHolder(view)
}
我的Firebase类
class FirestoreClass: BaseActivity() {
private val mFireStore = FirebaseFirestore.getInstance()
fun registerUser(activity: SignUpActivity, userInfo: User) {
mFireStore.collection(Constants.Users).document(getCurrentUserId()).set(userInfo,SetOptions.merge()).addOnSuccessListener {
activity.userRegisteredSuccess()
}.addOnFailureListener {
Log.e(activity.javaClass.simpleName, "Error Writing Document")
}
}
fun getCurrentUserId(): String {
val currentUser = FirebaseAuth.getInstance().currentUser
var currentUserId = ""
if(currentUser!=null) {
currentUserId = currentUser.uid
}
return currentUserId
}
fun loadUserData(activity: Activity, reaBoardList: Boolean = false) {
mFireStore.collection(Constants.Users).document(getCurrentUserId()).get().addOnSuccessListener { document ->
val loggedInUser = document.toObject(User::class.java)
if(loggedInUser!=null) {
when (activity) {
is SignInActivity -> {
activity.signInSuccess(loggedInUser)
}
is MainActivity -> {
activity.updateNavigationUserDetails(loggedInUser,reaBoardList)
}
is MyProfileActivity -> {
activity.setUserDataInUI(loggedInUser)
}
}
}
}.addOnFailureListener {
e ->
when (activity) {
is SignInActivity -> {
activity.hideProgressDialog()
}
is MainActivity -> {
activity.hideProgressDialog()
}
}
Log.e(activity.javaClass.simpleName,"Error Writin Document", e)
}
}
fun updateUserProfileData(activity: Activity, userHashMap: HashMap<String,Any>) {
mFireStore.collection(Constants.Users).document(getCurrentUserId()).update(userHashMap).addOnSuccessListener {
Log.i(activity.javaClass.simpleName,"Profile Data Updated")
Toast.makeText(activity,"Profile Updated Successfully!",Toast.LENGTH_SHORT).show()
when(activity) {
is MainActivity -> {
activity.tokenUpdateSuccess()
}
is MyProfileActivity -> {
activity.profileUpdateSuccess()
}
}
}.addOnFailureListener {
e->
when(activity) {
is MainActivity -> {
activity.hideProgressDialog()
}
is MyProfileActivity -> {
activity.hideProgressDialog()
}
}
Log.e(activity.javaClass.simpleName,"Error While Creating a Board",e)
Toast.makeText(activity,"Error When Updating the Profile!!",Toast.LENGTH_SHORT).show()
}
}
fun createBoard(activity: CreateBoardActivity, board: Board) {
mFireStore.collection(Constants.BOARDS).document().set(board,SetOptions.merge()).addOnSuccessListener {
Log.e(activity.javaClass.simpleName,"Board Created Successfully!")
Toast.makeText(activity,"Board Created Successfully",Toast.LENGTH_SHORT).show()
activity.boardCreatedSuccessfully()
}.addOnFailureListener {
Log.e(activity.javaClass.simpleName, "Error Writing Document")
}
}
fun getBoardList(activity: MainActivity) {
mFireStore.collection(Constants.BOARDS).whereArrayContains(Constants.ASSIGNED_TO, getCurrentUserId()).get().addOnSuccessListener {
document->
Log.i(activity.javaClass.simpleName, document.documents.toString())
val boardList: ArrayList<Board> = ArrayList()
for(i in document.documents) {
val board = i.toObject(Board::class.java)!!
board.documentId = i.id
boardList.add(board)
}
activity.populateBoardListToUI(boardList)
}.addOnFailureListener {
hideProgressDialog()
Log.e(activity.javaClass.simpleName,"Error While Creating a Board",it)
}
}
我的主要酸性
class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedListener {
private var binding: ActivityMainBinding? = null
private lateinit var mUserName: String
private lateinit var mSharedPref: SharedPreferences
private var mainMenu: Menu? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding?.root)
setActionBar()
mSharedPref = this.getSharedPreferences(Constants.PROMAG_PREFRENCES, MODE_PRIVATE)
val tokenUpdated = mSharedPref.getBoolean(Constants.FCM_TOKEN_UPDATED,false)
if(tokenUpdated) {
showProgressDialog("Please Wait ...")
FirestoreClass().loadUserData(this,true)
} else {
FirebaseInstanceId.getInstance()
.instanceId.addOnSuccessListener(this@MainActivity) { instanceIdResult ->
updateFCMToken(instanceIdResult.token)
}
}
binding?.navview?.setNavigationItemSelectedListener(this)
FirestoreClass().loadUserData(this,true)
binding?.appbar?.floatBoard?.setOnClickListener {
val intent = Intent(this@MainActivity,CreateBoardActivity::class.java)
intent.putExtra(Constants.NAME,mUserName)
startActivityForResult(intent, MY_BOARD_REQUEST_CODE)
}
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(resultCode==Activity.RESULT_OK && requestCode == MY_PROFILE_REQUEST_CODE) {
FirestoreClass().loadUserData(this)
} else if(resultCode==Activity.RESULT_OK && requestCode == MY_BOARD_REQUEST_CODE) {
FirestoreClass().getBoardList(this)
} else {
Log.e("Cancelled","Cancelled")
}
}
fun updateNavigationUserDetails(user: User,readBoardList: Boolean) {
hideProgressDialog()
mUserName = user.name
Glide
.with(this)
.load(user.image)
.centerCrop()
.placeholder(R.drawable.ic_nav_user)
.into(findViewById<CircleImageView>(R.id.hdoden))
val name = findViewById<TextView>(R.id.tvusername)
name.text = user.name
if(readBoardList) {
showProgressDialog("Please Wait ...")
FirestoreClass().getBoardList(this)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when(item.itemId) {
R.id.myprof -> {
startActivityForResult(Intent(this@MainActivity,MyProfileActivity::class.java),MY_PROFILE_REQUEST_CODE)
}
R.id.navsignout -> {
FirebaseAuth.getInstance().signOut()
mSharedPref.edit().clear().apply()
val intent = Intent(this@MainActivity,IntroActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
}
return true
}
fun populateBoardListToUI(boardList: ArrayList<Board>) {
hideProgressDialog()
if(boardList.size>0) {
binding?.appbar?.llmaincontent?.rvboardlist?.visibility = View.VISIBLE
binding?.appbar?.llmaincontent?.tvnoboardavailable?.visibility = View.GONE
binding?.appbar?.llmaincontent?.rvboardlist?.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
binding?.appbar?.llmaincontent?.rvboardlist?.setHasFixedSize(true)
val adapter = BoardItemAdapter(this,boardList)
binding?.appbar?.llmaincontent?.rvboardlist?.adapter = adapter
adapter.setOnClickListener(object: BoardItemAdapter.OnClickListener{
override fun onClick(position: Int, model: Board) {
val intent = Intent(this@MainActivity,TaskListActivity::class.java)
intent.putExtra(Constants.DOCUMENT_ID,model.documentId)
startActivity(intent)
}
})
} else {
binding?.appbar?.llmaincontent?.rvboardlist?.visibility = View.GONE
binding?.appbar?.llmaincontent?.tvnoboardavailable?.visibility = View.VISIBLE
}
}
private fun setActionBar() {
setSupportActionBar(binding?.appbar?.toolbarmainacivity)
binding?.appbar?.toolbarmainacivity?.setNavigationIcon(R.drawable.ic_hamburger)
binding?.appbar?.toolbarmainacivity?.setNavigationOnClickListener {
if(binding?.drawerl?.isDrawerOpen(GravityCompat.START)==true) {
binding?.drawerl?.closeDrawer(GravityCompat.START)
} else {
binding?.drawerl?.openDrawer(GravityCompat.START)
}
}
}
fun tokenUpdateSuccess() {
hideProgressDialog()
val editor : SharedPreferences.Editor = mSharedPref.edit()
editor.putBoolean(Constants.FCM_TOKEN_UPDATED,true)
editor.apply()
showProgressDialog("Please Wait ...")
FirestoreClass().loadUserData(this,true)
}
private fun updateFCMToken(token:String) {
val userHashMap = HashMap<String,Any>()
userHashMap[Constants.FCM_TOKEN] = token
showProgressDialog("Please Wait ...")
FirestoreClass().updateUserProfileData(this,userHashMap)
}
override fun onBackPressed() {
super.onBackPressed()
if(binding?.drawerl?.isDrawerOpen(GravityCompat.START)==true) {
binding?.drawerl?.closeDrawer(GravityCompat.START)
} else {
doubleBackToExit()
}
}
companion object{
const val MY_PROFILE_REQUEST_CODE: Int = 11
const val MY_BOARD_REQUEST_CODE: Int = 12
}
}
正如Alex mano所提到的,您可以按照blog1和blog2进行操作,其中提供了有关从回收器视图上的fi恢复中删除单个或多个记录的简要信息。
有关更多信息,您可以按照thread1和thread2进行说明,其中解释了从回收器视图上的fi恢复中删除项目或节点。代码示例:
@Override
public void onDeleteClick(int position) {
Upload selectedItem = mUploads.get(position);
StorageReference imageRef = mStorage.getReferenceFromUrl(selectedItem.getmImageUrl());
View view = LayoutInflater.from(ShowPatientsRecords.this).inflate(R.layout.alertdelet null);
Button no = view.findViewById(R.id.dltNo);
Button yes = view.findViewById(R.id.dltYes);
AlertDialog dialog = new AlertDialog.Builder(ShowPatientsRecords.this).setView(view).create();
dialog.setCancelable(false);
dialog.show();
yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Upload selectedItem = mUploads.get(position);
final String selectedKey = selectedItem.getmKey();
imageRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
mDatabaseRef.child(selectedKey).removeValue();
dialog.dismiss();
Toast.makeText(ShowPatientsRecords.this, "Record deleted", Toast.LENGTH_LONG).show();
}
});
}
});
no.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
}