0

EditFragment должен получать текст от пользователя и передавать его в NotesFragment для добавления в список (recycleView). Хочу использовать setFragmentResult, но у меня ничего не выходит. Должна ли здесь быть задействована Activity? Помогите, пожалуйста.


class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        startNotesFragment()

        initListeners()
    }


    private fun initListeners() {
        binding.bAdd.setOnClickListener {
            startEditFragment()
        }
    }

    private fun startEditFragment() {
        supportFragmentManager.beginTransaction()
            .replace(R.id.fl_container, EditFragment.newInstance()).addToBackStack(null).commit()

    }

    private fun startNotesFragment() {
        supportFragmentManager.beginTransaction().replace(
            R.id.fl_container,
            NotesFragment.newInstance()
        ).addToBackStack(null).commit()

    }
}




class EditFragment : Fragment() {
    private var binding: FragmentEditBinding? = null

    companion object {
        fun newInstance() = EditFragment()
    }
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        binding = FragmentEditBinding.inflate(layoutInflater)

        return binding?.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding!!.bUndo.setOnClickListener {
            activity?.onBackPressed()
        }
        binding?.bSave?.setOnClickListener {
           val result = binding!!.etAuthorText.text.toString()
            setFragmentResult("key", bundleOf("bundleKey" to result))
            activity?.onBackPressed()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        binding = null
    }

}



class NotesFragment : Fragment() {
    private var binding: FragmentListBinding? = null
    private val adapter = NoteAdapter()

    companion object {
        fun newInstance() = NotesFragment()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding!!.rcList.layoutManager = LinearLayoutManager(context)
        binding!!.rcList.adapter = adapter
        setFragmentResultListener("key") { key, bundle ->
            val result = bundle.getString("bundleKey")
            if (result != null) {
                adapter.addNote(result)
            }
        }
    }
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentListBinding.inflate(layoutInflater)
        return binding?.root

    }


    override fun onDestroy() {
        super.onDestroy()
        binding = null
    }
}


class NoteAdapter : RecyclerView.Adapter<NoteAdapter.NoteHolder>() {
    private val noteList = ArrayList<String>()

    class NoteHolder(item: View) : RecyclerView.ViewHolder(item) {
        private val binding = MyListItemBinding.bind(item)
        fun bind(authorText: String) = with(binding) {
            tvMessage.text = authorText
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.my_list_item, parent, false)
        return NoteHolder(view)
    }

    override fun onBindViewHolder(holder: NoteHolder, position: Int) {
        holder.bind(noteList[position])
    }

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

    fun addNote(note: String) {
        noteList.add(note)
        notifyDataSetChanged()
    }
}

1 ответ 1

0

Попробуйте использовать supportFragmentManager вашего Activity.

Для отслеживания результата:

activity?.supportFragmentManager?.setFragmentResultListener(
        "key",
        viewLifecycleOwner,
        { requestKey, result ->
            TODO("Not yet implemented")
        })

Для передачи данных:

activity?.supportFragmentManager?.setFragmentResult("key",  bundleOf("bundleKey" to result))

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.