数据未从 activity 传输到片段

Data is not transferred from activity to fragment

我正在尝试写入从 activity 到片段的数据传输,但我正在捕获“NullPointerException” 代码 MainActivity:

val btn1 = findViewById<Button>(R.id.button)
        btn1.setOnClickListener {
            BlankFragment2.getNewInstance(321)
            val fm = supportFragmentManager
            val ft = fm.beginTransaction()
            ft.replace(R.id.fragment, BlankFragment2())
            ft.commit()
        }

代码片段:

class BlankFragment2 : Fragment() {
    var str: Int = 0
    companion object {
        fun getNewInstance(args: Int): BlankFragment2 {
            val fragment = BlankFragment2()
            fragment.arguments?.putInt("one", args)
            return fragment
        }
    }
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        str = arguments!!.getInt("one")
        
        return inflater.inflate(R.layout.fragment_blank2, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val txt = view.findViewById<TextView>(R.id.textTest)
        txt.text = str.toString()
    }
}

我知道防止空值的保护,问题是我确定该值已传递,但不能存在空值

而不是
ft.replace(R.id.fragment, BlankFragment2()

你应该使用

ft.replace(R.id.fragment, BlankFragment2.getNewInstance(321).

因为您上面的 BlankFragment2.getNewInstance(321) 语句对 fragmentManager 有点无用。 FragmentManager 正在使用 BlankFragment2() 创建片段,因为您在 replace 调用中提供了片段。 这就是 nullpointerexception 的原因,因为实际上,您的 Fragment 根本没有获得任何 int 值,因为使用的 Fragment 实例是用空构造函数创建的。

并像下面这样更新您的伴随对象代码。

 companion object {
        fun getNewInstance(args: Int): BlankFragment2 {
            val fragment = BlankFragment2()
            val args = Bundle()
            args.putInt("one", args)
            fragment.setArguments(args)
            return fragment
        }
    }

因为现在您的代码实际上并未设置参数,而是尝试访问参数并为其设置值。