как данные из экземпляра HolderView можно передать в другой activity? Так же через Intent пытаться?

adapter

package codes.myappnotes

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import codes.myappnotes.databinding.TemplateItemNoteBinding

class AdapterNote : RecyclerView.Adapter<AdapterNote.HolderView>() {
    var array = ArrayList<Note>()

    class HolderView(item: View): RecyclerView.ViewHolder(item) {
        private val binding = TemplateItemNoteBinding.bind(item)
        fun bind(note: Note) = with(binding) {
            headerNote.text = note.header
            textNote.text = note.text
        }
    }

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HolderView {
    /** Данный метод создаёт экземпляр класса HolderView **/
    val view = LayoutInflater.from(parent.context).inflate(R.layout.template_item_note, parent, false)
    return HolderView(view)
}

override fun onBindViewHolder(holder: HolderView, position: Int){
    /** Данный метод заполняет экземпляр класса HolderView данными **/
    holder.bind(array[position])
    println(position)
}

override fun getItemCount(): Int {
    /** Общее количество данных которое нужно вывести в RecyclerView **/
    return array.size
}

@SuppressLint("NotifyDataSetChanged")
fun addNote(note: Note) {
    /** Данный метод добавляет данные в массив и обновляет RecyclerView **/
    array.add(note)
    notifyDataSetChanged()
}

@SuppressLint("NotifyDataSetChanged")
fun removeNote(note: Note) {
    /** Данный метод удаляет заметку **/
    array.remove(note)
    notifyDataSetChanged()
}

@SuppressLint("NotifyDataSetChanged")
fun changeNote(index: Int, note: Note) {
    /** Данный метод изменяет содержимое заметки **/
    array.add(index, note)
    notifyDataSetChanged()
}
}

activity в которую нужно передать данные

package codes.myappnotes

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.TextView

class PageNotesActivity : AppCompatActivity() {
    private val adapter = AdapterNote()
    private val array = ArrayList<Note>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_page_notes)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            finish()
        }

        R.id.delete -> {

        }

        R.id.change -> {

        }
    }
    return true
}

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.page_note, menu)
    return true
}

fun addNote(note: Note) {
    array.add(note)
}
}

MainActivity

package codes.myappnotes

import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import codes.myappnotes.databinding.ActivityMainBinding
import codes.myappnotes.databinding.ActivityPageNotesBinding
import codes.myappnotes.db.DataBaseManager
import com.google.android.material.floatingactionbutton.FloatingActionButton

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val adapter = AdapterNote()
    private var editlaunch: ActivityResultLauncher<Intent>? = null
    private val dataBaseManager = DataBaseManager(this)
    private val pageNotesActivity = PageNotesActivity()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        init()
         editlaunch = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode == RESULT_OK) {
            adapter.addNote(it.data?.getSerializableExtra("Note") as Note)
        }
    }
}

override fun onResume() {
    super.onResume()
    if (adapter.array.size == 0) {
        findViewById<TextView>(R.id.textView2).text = "Пусто"
    } else {
        findViewById<TextView>(R.id.textView2).text = ""
    }
}

@SuppressLint("CutPasteId")
private fun init() {
    apply {
        findViewById<RecyclerView>(R.id.recyclerView).layoutManager = GridLayoutManager(this@MainActivity, 1)
        findViewById<RecyclerView>(R.id.recyclerView).adapter = adapter

        findViewById<FloatingActionButton>(R.id.floatingActionButton).setOnClickListener {
            editlaunch?.launch(Intent(this@MainActivity, AddNoteActivity::class.java))
        }
    }
}
}

Ответы (1 шт):

Автор решения: Andrew

Можно сделать интерфейс и при его помощи передавать данные:

interface CallbackInterface {   
        fun passResultCallback(message: String)
    }

добавить его в конструктор адаптера:

class AdapterNote(private val callbackInterface:CallbackInterface) :
    RecyclerView.Adapter<AdapterNote.HolderView>() {
.
.
.
}

дальше в слушателе нажатий на элемент списка добавляете вызов метода интерфейса:

holder.itemView.setOnClickListener {
     callbackInterface.passResultCallback("Your message")
}

и в активности добавляете использование адаптера:

class MainActivity: AppCompatActivity(),CallbackInterface {
...
override fun passResultCallback(message: String) {
         
    }
...
}

ну и дальше уже Intent использовать чтобы передавать информацию дальше в другую активность. В моем примере мы передаем строку, но вы можете поменять тип передаваемых данных на нужный вам.

→ Ссылка