【问题标题】:How to use bindings to access BottomAppBar in Activity from Fragment?如何使用绑定从 Fragment 访问 Activity 中的 BottomAppBar?
【发布时间】:2021-05-25 07:43:26
【问题描述】:

我已从 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: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // how can i access the bottomAppBar from the activity at this point?
    }

删除 kotlin 扩展后,我在第一个代码块上得到 Unresolved reference: bottomAppBar..

【问题讨论】:

  • 使用 fragmentCorpoBinding.bottomAppBar
  • @AlphaOne bottomAppBar 设置在Activity中,所以fragmentCorpoBinding.bottomAppBar仍然返回Unresolved reference: bottomAppBar
  • 这是一种奇怪的做法,但无论如何。您需要将Activity 中的绑定设为公开,然后您可以使用(activity as LetturaActivity).binding.bottomAppBar 访问它。

标签: android kotlin android-databinding


【解决方案1】:

可以通过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 都应该有其独立的视图(关注点分离)。 如果你真的需要它,只需在你的 Activity 中添加这样的东西:

class LetturaActivity {

 fun updateBottomMenu() {
  binding.bottomAppBar.navigationIcon = ContextCompat.getDrawable(
            requireContext(),
            R.drawable.ic_baseline_menu_24
        )
 }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多