使用实时数据在片段之间共享数据。但是,在第二个片段中,数据未观察到

问题描述 投票:0回答:2

我正在使用实时数据在两个片段之间共享数据。但是,第二个片段中的数据根本看不到,所以我无法获取数据。

ViewModel

    var selectedAttachment = MutableLiveData<ArrayList<Attachment>>()
    private val attachmentList = ArrayList<Attachment>()

    private fun getExistingAttachmentPos(key: String): Int{
        return attachmentList.indexOfFirst { att -> att.name == key}
    }

    fun toggleAttachment(attachment: Attachment){
        val id = attachment.name
        val pos = getExistingAttachmentPos(id)
        if(pos == -1 ){
            attachmentList.add(attachment);
        }else{
            attachmentList.removeAt(pos);
        }
        selectedAttachment.postValue(attachmentList)
    }

不久,可以设置和观察第一个片段中的数据

firstfragment

    private fun observeHorizontalAttachment(){
        viewModel.selectedAttachment.observe(viewLifecycleOwner, Observer<ArrayList<Attachment>>{
            if(it.size>3){
                Log.d("tag63", it.toString())
                wrapPlus3.visibility = View.VISIBLE
                plus3.text = "+${(it.size - 3).toString()}"
                pendingAttachment.clear()
                pendingAttachment.addAll(it)
                (rvAttachment.adapter as AttachmentAdapter).setDataset(it)
            }else{
                pendingAttachment.clear()
                pendingAttachment.addAll(it)
                Log.d("tag3", "kurang dari 3 ${it.size}")
                wrapPlus3.visibility = View.GONE
            }
        })
    }

第一片段中的数据存在/可观察

secondfragment

   private fun attachmentObserve(){
        viewModel.selectedAttachment.observe(viewLifecycleOwner, Observer<ArrayList<Attachment>>{
                Log.d("tag6",  it.toString())
                pendingAttachment.clear()
                pendingAttachment.addAll(it)
        })
    }

    private fun handleRvAttachment(){
        Log.d("tag61",  pendingAttachment.toString())
        rvListAttachment.apply {
            adapter = ListAttachmentAdapter(pendingAttachment)
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        }
    }

在第二个片段中,selectedAttachment根本看不到(即使'tag6'也未调试),所以我无法获取数据

谢谢。

android kotlin viewmodel android-livedata
2个回答
2
投票

SharedViewModel在这种情况下将为您工作。您可以像下面这样使用:

[FirstFragmentSecondFragment相同

activity?.let {
        yourViewModel = ViewModelProvider(it).get(YourViewModel::class.java)

        yourViewModel.selectedAttachment.observe(viewLifecycleOwner, Observer<ArrayList<Attachment>> {
            Log.d("tag6", it.toString())
            pendingAttachment.clear()
            pendingAttachment.addAll(it)
        })
    }

activity的位置可按以下方式使用,如果您正在观察activity

viewModel = ViewModelProvider(this).get(YourViewModel::class.java)

ViewModelProvider(this)也可以直接替换为by activityViewModels(),可以像by activityViewModels()一样实现


0
投票

我更改了用于从中声明视图模型的声明方法thisprivate val viewModel: ChatListViewModel by inject()

© www.soinside.com 2019 - 2024. All rights reserved.