簡體   English   中英

如何在 kotlin 中將數據從一個片段傳遞到另一個片段?

[英]How to pass data from one fragment to another in kotlin?

我的 Android 應用程序中有一個 ViewPager2,我是 Kotlin 和片段的新手,在片段的第一個選項卡中,我有一個按鈕,可以在數據庫中創建記錄並返回創建行的 ID,然后我以編程方式切換到另一個帶有另一個片段的選項卡,其中一些字段要填充片段 1 中創建的行中的數據。

此時,我必須獲取我在片段 2 中的片段 1 中獲得的 id,以調用我的 function,它根據我的數據庫中的 id 返回數據。

但是如何將我在片段 1 中獲得的 id 傳遞給片段 2?

這是我的片段1:

class ElencoFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_elenco, container, false)
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ...
        btnNuovo.setOnClickListener {
            corpoViewModel.insertTestata( // inserting data to database and get the id back
                Testata(
                    "",
                    tipo,
                    "",
                    "",
                    data,
                    true
                )
            ).observe(viewLifecycleOwner) {
                Toast.makeText(requireContext(), it.toString(), Toast.LENGTH_LONG).show() // here i have the id
            }
            viewPager.setCurrentItem(1, false) // changing the PageView to Tab 2 where i have another fragment with the fields to be filled
    }
}

一種簡單的方法是在您的父Activity中存儲一個公共變量並將其修改為它的 Fragment 子項。

首先,在你的父Activity中聲明一個全局變量

var selectedId = -1

然后,您可以在您的片段中訪問它(使用您的活動的真實名稱更改ParentActivity ):

(activity as ParentActivity).selectedId = newValue  // Setter

val id = (activity as ParentActivity).selectedId    // Getter

因此,根據您的第一個片段的代碼,您應該分配 id 值

btnNuovo.setOnClickListener {
            corpoViewModel.insertTestata( // inserting data to database and get the id back
                Testata(
                    "",
                    tipo,
                    "",
                    "",
                    data,
                    true
                )
            ).observe(viewLifecycleOwner) {
                (activity as ParentActivity).selectedId = it
            }

然后在你的第二個片段中檢索它,如上所述。

要傳遞您的數據,您可以使用片段包,

Bundle().apply {
        putInt(KEY, imageDrawable)
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM