即使我没有声明它,Bundle也可以为空

时间:2018-05-16 14:59:07

标签: android kotlin nullable

class UserFragment : Fragment(), View.OnClickListener {

private val userBinding: FragmentUserBinding by onCreateView<Fragment, FragmentUserBinding>(R.layout.fragment_user)
val user: ObservableField<String> = ObservableField()
private var bundle = Bundle()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    userBinding.main = this
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = userBinding.root!!

override fun onClick(p0: View?) {
    runAnimation(500L, Techniques.RubberBand, p0)
    Handler().postDelayed({
        saveUserAndStartLetterFragment()
    }, 700L)
}

private fun saveUserAndStartLetterFragment() {
    var fragment = WordpackChooserFragment()
    bundle.putString("User",user.get())
    fragment.arguments = bundle
    activity!!.supportFragmentManager.replaceFragment(fragment, activity!!.findViewById(R.id.flContainer))
}
}

在这个片段中,我声明了这个包。我没有将其指定为可空。

class WordpackChooserFragment : Fragment(), View.OnClickListener {

private val wordpackChooserBinding: FragmentWordpackChooserBinding by onCreateView<Fragment, FragmentWordpackChooserBinding>(R.layout.fragment_wordpack_chooser)
private var bundle: Bundle = Bundle()
private lateinit var fragment: Fragment

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    wordpackChooserBinding.main = this
    setRecycler()
    bundle = arguments
    return wordpackChooserBinding.root
}

override fun onClick(v: View?) {
    fragment = RoundsChooserFragment()
    bundle.putStringArrayList("Wordpack", selectedPack)
    fragment.arguments = bundle
    activity!!.supportFragmentManager.replaceFragment(fragment, activity!!.findViewById(R.id.flContainer))
}

private fun setRecycler() {
    wordpackChooserBinding.root.btn_recycler.layoutManager = LinearLayoutManager(this.context)
    wordpackChooserBinding.root.btn_recycler.adapter = BtnAdapter(this)
    wordpackChooserBinding.root.btn_recycler.adapter.notifyDataSetChanged()
}

}

在此片段中,此行bundle = arguments出现以下错误:

类型不匹配。

必需:捆绑

发现:捆绑?

我可以使用非null断言运算符'!!'但这似乎是一个黑客。

1 个答案:

答案 0 :(得分:3)

argumentsnullable(请注意&#34;如果有#34;在链接描述中),因此您不能简单地将其分配给不可为空的{{1} }。您可以使用Bundle处理null(使用if),也可以使用!!来处理它的情况:

arguments?.let { bundle = it }

但是,我说它更喜欢使用let