删除Kotlin中的项目后如何更新android中的recycleView?

时间:2020-06-16 05:14:29

标签: android kotlin android-recyclerview

我创建了一个回收视图,并在其中使用卡片视图创建了物品。每当我单击卡片视图中的项目时,就会从SQLite数据库中删除该项目。但是要在UI上反映出来,应用需要重新启动。如何通知adpater该项目已删除?

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    tools:context=".MainActivity">

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:layout_width="57dp"
        android:layout_height="64dp"
        android:layout_marginEnd="40dp"
        android:layout_marginBottom="40dp"
        android:clickable="true"
        android:onClick="addNewCredentials"
        app:backgroundTint="#270867"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:srcCompat="@android:drawable/ic_menu_add" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="1dp"
        android:layout_marginTop="1dp"
        android:layout_marginEnd="1dp"
        android:layout_marginBottom="1dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" >

    </androidx.recyclerview.widget.RecyclerView>

</androidx.constraintlayout.widget.ConstraintLayout>

list_item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/urlView"
                android:layout_width="300dp"
                android:layout_height="30dp"
                android:layout_marginTop="16dp"
                android:layout_marginBottom="16dp"
                android:text="url"
                android:textAppearance="@style/TextAppearance.AppCompat.Large"
                android:textSize="24sp"
                android:textStyle="bold"
                app:layout_constraintBottom_toTopOf="@+id/userNameView"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.1"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="1.0" />

            <TextView
                android:id="@+id/userNameView"
                android:layout_width="300dp"
                android:layout_height="25dp"
                android:layout_marginBottom="16dp"
                android:text="userName"
                app:layout_constraintBottom_toTopOf="@+id/passwordView"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.1"
                app:layout_constraintStart_toStartOf="parent" />

            <TextView
                android:id="@+id/passwordView"
                android:layout_width="300dp"
                android:layout_height="25dp"
                android:layout_marginBottom="16dp"
                android:text="password"
                app:layout_constraintBottom_toTopOf="@+id/noteView"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.1"
                app:layout_constraintStart_toStartOf="parent" />

            <TextView
                android:id="@+id/noteView"
                android:layout_width="300dp"
                android:layout_height="30dp"
                android:layout_marginBottom="16dp"
                android:text="note"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.1"
                app:layout_constraintStart_toStartOf="parent" />

            <Button
                android:id="@+id/delButton"
                android:layout_width="78dp"
                android:layout_height="40dp"
                android:layout_marginEnd="8dp"
                android:layout_marginBottom="36dp"
                android:background="#E6360F"
                android:text="@string/delete_credential_button"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent" />

        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>
</LinearLayout>

MainActivity.kt

package com.example.passwordmanager

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL,false)
        val db = DataBaseHandler(this)
        val detailsData = db.readCredentials()
        val adapter = CredentialAdapter(detailsData,this,{credentialsModel: CredentialsModel->deleteClick(credentialsModel)})
        recyclerView.adapter = adapter
    }

    fun deleteClick(credential: CredentialsModel){
        val db = DataBaseHandler(this)
        if(db.deleteData(credential.id)){
            //adapter.notifyItemRemoved(position)
            Toast.makeText(applicationContext,"Deleted", Toast.LENGTH_SHORT).show()
        }
    }

    fun addNewCredentials(view : View){
        print("hello world")
        val intent = Intent(this, AddDetailActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        startActivity(intent)
    }
}

CredentialAdapter.kt

package com.example.passwordmanager

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.list_item_layout.view.*

class CredentialAdapter(
    private val items: List<CredentialsModel>,
    ctx: Context, val clickListener: (CredentialsModel) -> Unit
): RecyclerView.Adapter<CredentialAdapter.ViewHolder>() {
    var context = ctx
    class ViewHolder(itemView: View):RecyclerView.ViewHolder(itemView){
        fun bind(credential: CredentialsModel,clickListener: (CredentialsModel) -> Unit){
            itemView.urlView.text = credential.url
            itemView.userNameView.text = credential.userName
            itemView.passwordView.text = credential.password
            itemView.noteView.text = credential.note
            itemView.delButton.setOnClickListener{clickListener(credential)}
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.list_item_layout,parent,false))
    }

    override fun getItemCount(): Int {
        return items.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val credential:CredentialsModel = items[position]
        holder.bind(credential,clickListener)
    }
}

4 个答案:

答案 0 :(得分:1)

在您的onBindViewHolder中添加删除setOnClickListener。

sender.value

答案 1 :(得分:1)

处理此类情况的最佳方法是使用LiveData。 LiveData基本上是一个可观察的类,仅在发生更改时才读取数据。 您可以做的是在适配器中创建一个set函数,例如:

 internal fun setData(data: List<Data>) {
    this.data= dataList //this datalist is a list defined in your adapter 
    notifyDataSetChanged()
}

现在在您的主要活动/片段中,在onCreate函数之外创建一个LiveData列表,如下所示:

private lateinit var allData:LiveData<List<Data>>

现在在您的onCreate函数中,用户可以观察实时数据并为recyclerview设置数据,如下所示:

allData.observe(this, Observer { data->
        data?.let { adapter.setData(it) }
    })

答案 2 :(得分:0)

您要从数据库中删除项目,而不是从recyclerview适配器中的列表中删除项目。

class CredentialAdapter(
private val items: ArrayList<CredentialsModel>, // Change list to arraylist
ctx: Context, val clickListener: (CredentialsModel, Int) -> Unit
): RecyclerView.Adapter<CredentialAdapter.ViewHolder>() {

    ...
    ...

    fun remove(position: Int) {
        // Remove and notify the adapter to reload
        items.removeAt(position)
        notifyItemRemoved(position)
    }

    class ViewHolder(itemView: View):RecyclerView.ViewHolder(itemView) {
        fun bind(credential: CredentialsModel,clickListener: (CredentialsModel, Int) -> Unit){
            ...
            ...
            // Pass adapter item position so that we can update the list after delete
            itemView.delButton.setOnClickListener{clickListener(credential, adapterPosition)
        }
    } 

    ...
    ...
}

MainActivity.kt内部

fun deleteClick(credential: CredentialsModel, position: Int) {
    val db = DataBaseHandler(this)
    if(db.deleteData(credential.id)){
        adapter.remove(position)
        Toast.makeText(applicationContext,"Deleted", Toast.LENGTH_SHORT).show()
    }
}

答案 3 :(得分:0)

使用ListAdpater

foo['percentage'] = foo['val'].eq(1).groupby(foo['id']).transform('mean')

}

you can see complete code of simple NoteApp with kotlin , recyclerView , MVVM and..