提问者:小点点

数据不从activity转移到片段


我正在尝试编写一个从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()
    }
}

我知道对空值的保护,但问题是,我确信传递了值,而null不在那里


共1个答案

匿名用户

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

您应该使用

ft.replace(r.id.fragment,blankfragment2.getnewInstance(321)

因为上面的blankfragment2.getnewInstance(321)语句对FragmentManager来说是无用的。FragmentManager正在使用blankFragment2()创建片段,就像您在replace调用中提供的片段一样。这就是nullpointerexception的原因,因为实际上,您的片段根本没有得到任何int值,因为所使用的片段实例是用空构造函数创建的。