Kotlin: удаление списка в Recycerview с помощью кнопки AlertDialog - PullRequest
0 голосов
/ 20 марта 2020

Я надеюсь удалить элементы в Recyclerview с помощью кнопки AlertDialog. У вас есть идея?

Адаптер и видоискатель

class ProjectsRecyclerAdapter(val list:List<ProjectListDataModel>, var clickListner: OnProjectListClickListner) : RecyclerView.Adapter<ProjectRecyclerViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProjectRecyclerViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cardview, parent, false)
        return ProjectRecyclerViewHolder(
            view
        )
    }

    override fun getItemCount(): Int {
        return list.count()
    }

    override fun onBindViewHolder(holder: ProjectRecyclerViewHolder, position: Int) {
        holder.initialize(list[position], clickListner)

    }
}

class ProjectRecyclerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    fun initialize(item: ProjectListDataModel, action: OnProjectListClickListner) {
        itemView.projectNameText.text = item.name
        itemView.modifiedTimeText.text = item.modTime
        itemView.descriptionText.text = item.description

        itemView.setOnClickListener {
            action.onItemClick(item, adapterPosition)
        }

    }
}

interface  OnProjectListClickListner {
    fun onItemClick(item: ProjectListDataModel, position: Int)
}

А вот и основное занятие

class LocalProjectListActivity :
    AppCompatActivity(),
    OnProjectListClickListner,
    NavigationView.OnNavigationItemSelectedListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main)

        val localProjectList = listOf(
            ProjectListDataModel(
                "Project A",
                "Sun, 01/DEC/2020, 22:23GMT",
                "Testing 1",
                "AAAA",
                "A, A",
                8,
                232
            ),
            ProjectListDataModel(
                "Project B",
                "Sun, 01/JUL/2020, 10:23GMT",
                "Testing 2",
                "BBBB",
                "B, B",
                6,
                354
            ),
            ProjectListDataModel(
                "Project C",
                "Sun, 11/MAR/2020, 08:31GMT",
                "Testing 3",
                "CCCC",
                "C,C",
                15,
                632
            )
        )

        val adapter = ProjectsRecyclerAdapter(localProjectList, this)
        projectNameText.adapter = adapter
        projectNameText.setHasFixedSize(true)
        projectNameText.layoutManager = LinearLayoutManager(this)
    }

    override fun onItemClick(item: ProjectListDataModel, position: Int) {

        val builder = AlertDialog.Builder(this)
        val ad = builder.create()
        val dialogView = layoutInflater.inflate(R.layout.project_onclick, null)
        dialogView.projectNameText.text = item.name
        dialogView.modifiedTimeText.text = item.modTime
        dialogView.descriptionText.text = item.description
        dialogView.fileNumberText.text = item.fileNumber.toString() + "EA"
        dialogView.fileSizeText.text = item.fileSize.toString() + "MB"
        dialogView.scopeText.text = item.scope
        dialogView.userIdText.text = item.resposible
        ad.setView(dialogView)
        ad.show()


        //when click Load button
            dialogView.loadButton.setOnClickListener {
            ad.dismiss()

            val dialog = AlertDialog.Builder(this)
            dialog.setTitle("Question1")
            dialog.setMessage("You want to go to the project?")
            dialog.setPositiveButton("Yes", DialogInterface.OnClickListener { _, _ ->
            })
            dialog.setNegativeButton("No", DialogInterface.OnClickListener { _, _ ->
                val fileFilterIntent = Intent(this, ProjectFileActivity::class.java)
                startActivity(fileFilterIntent)
            })
            dialog.setNeutralButton("Cancel", DialogInterface.OnClickListener {dialog, _ ->
                dialog.dismiss()
            })
            //if(isMarker == true) {
            dialog.show()
            //} else {}
        }

        dialogView.deleteButton.setOnClickListener {
            ad.dismiss()

            val dialog = AlertDialog.Builder(this)

            dialog.setTitle("Delet project list")
            dialog.setMessage("You want to delete project?")
            dialog.setPositiveButton("Yes", DialogInterface.OnClickListener { _, _ ->
                **//Delete items in RecyclerView**
            })
            dialog.setNeutralButton("Cancel", null)
            dialog.show()
        }
        dialogView.cancleButton.setOnClickListener { ad.dismiss() }
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.remoteProjects -> {
                val serverProjIntent = Intent(this, ServerProjectListActivity::class.java)
                startActivity(serverProjIntent)
            }
            R.id.settings -> {
                Toast.makeText(this, "Go to Settings", Toast.LENGTH_SHORT).show()
            }
        }

        mainLocal.closeDrawer(GravityCompat.START)
        return true
    }

}

Я разместил весь код подобным образом. Я могу получить списки, используя Recyclerview, и создал AlertDialog, но я не знаю, как удалить элементы с помощью кнопки «Да» в AlertDialog.

Пожалуйста, дайте мне несколько советов.

1 Ответ

1 голос
/ 20 марта 2020

Вам нужно иметь ссылку на список и адаптер вне onCreate

private val localProjectList = mutableListOf(
    ProjectListDataModel(
        "Project A",
        "Sun, 01/DEC/2020, 22:23GMT",
        "Testing 1",
        "AAAA",
        "A, A",
        8,
        232
    ),
    ProjectListDataModel(
        "Project B",
        "Sun, 01/JUL/2020, 10:23GMT",
        "Testing 2",
        "BBBB",
        "B, B",
        6,
        354
    ),
    ProjectListDataModel(
        "Project C",
        "Sun, 11/MAR/2020, 08:31GMT",
        "Testing 3",
        "CCCC",
        "C,C",
        15,
        632
    )
)

private lateinit var adapter: ProjectsRecyclerAdapter

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main)

    adapter = ProjectsRecyclerAdapter(localProjectList, this)
    projectNameText.adapter = adapter
    projectNameText.setHasFixedSize(true)
    projectNameText.layoutManager = LinearLayoutManager(this)
}

, а затем удалить список и уведомить адаптер

private fun deleteItemsAndNotifyAdapter() {
    localProjectList.clear()
    adapter.notifyDataSetChanged()
}

Вы можете удалить и уведомить адаптер в диалоговом окне:

private var alertDialog: AlertDialog? = null
private fun showDeleteDialog() {
    val builder = AlertDialog.Builder(activity)
    builder.run {
        setTitle("Delete project list")
        setMessage("You want to delete project?")
        setPositiveButton("Yes") { _, _ ->
            deleteItemsAndNotifyAdapter()
        }
        setNegativeButton("Cancel") { _, _ ->
        }
    }

    alertDialog = builder.create()
    alertDialog?.show
}
...