Activity给Fragment传值
1.钩子Bundle
val fragment = ScreenSlideFragment() val bundle = Bundle() bundle.putString("LOCATION","蜀山") fragment.arguments = bundle
创建一个Fragment
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentScreenSlideBinding.inflate(layoutInflater)
val location = arguments?.get("LOCATION")
Log.i("ScreenSlideFragment","location = " + location)
binding.location.text = location as CharSequence?
// Inflate the layout for this fragment
return binding.root
}
2.在Fragment里覆盖这个方法,从宿主Context里直接调用
override fun onAttach(context: Context) {
super.onAttach(context)
val location = (context as MainActivity).getLocation()
binding = FragmentScreenSlideBinding.inflate(layoutInflater)
binding.location.text = location
}
评论
发表评论