如何解决如何使用绑定从 Fragment 访问 Activity 中的 BottomAppBar?
由于 kotlin-extention
已被弃用,我已从 extention
转移到绑定用法,因此我正在使用绑定重建整个应用程序。
我在从位于我的 Activity 中的片段访问 BottomAppBar 时遇到问题。
在绑定之前,我使用的代码如下:
class CorpoFragment : Fragment() {
override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
super.onViewCreated(view,savedInstanceState)
(activity as LetturaActivity).bottomAppBar.navigationIcon = ContextCompat.getDrawable(
requireContext(),R.drawable.ic_baseline_menu_24
)
}
}
但现在我已经在该片段中设置了绑定,例如:
class CorpoFragment : Fragment() {
private var fragmentCorpoBinding: FragmentCorpoBinding? = null
override fun onCreateView(
inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?
): View {
val binding = FragmentCorpoBinding.inflate(inflater,container,false)
fragmentCorpoBinding = binding
return binding.root
}
override fun onViewCreated(view: View,savedInstanceState)
// how can i access the bottomAppBar from the activity at this point?
}
删除 kotlin-extention 后,我在第一个代码块上得到了 Unresolved reference: bottomAppBar
..
解决方法
变量可通过 binding
类访问。
private lateinit var binding: FragmentCorpoBinding
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View {
binding = FragmentCorpoBinding.inflate(inflater,container,false)
return binding.root
}
override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
super.onViewCreated(view,savedInstanceState)
binding.bottomAppBar
}
我建议您不要访问从 Fragment 到 Activity 的视图元素,因为每个 Activity/Fragment 都应该有其独立的视图(关注点分离)。 如果你真的需要它,只需在你的活动中添加这样的东西:
class LetturaActivity {
fun updateBottomMenu() {
binding.bottomAppBar.navigationIcon = ContextCompat.getDrawable(
requireContext(),R.drawable.ic_baseline_menu_24
)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。