【问题标题】:Error trying to generate Binding class for my Fragment尝试为我的片段生成绑定类时出错
【发布时间】:2020-07-08 20:19:42
【问题描述】:

我有以下 XML 文件,它是我的 Fragment 的布局 -

<?xml version="1.0" encoding="utf-8"?>

<layout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:orientation="vertical"
        android:padding="15dp"
        tools:context=".fragments.DashboardFragment">

        <androidx.viewpager2.widget.ViewPager2
            android:id="@+id/fragment_dashboard_viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

</layout>

FragmentDashboardBinding 类确实是自动生成的,但我不能使用它 -

class DashboardFragment : Fragment(R.layout.fragment_dashboard) {

    private lateinit var binding : FragmentDashboardBinding


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = FragmentDashboardBinding.inflate(inflater, container, false)
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }

}

我在尝试构建项目时遇到了我在顶部看到的错误,使其无法使用

我错过了一些东西。会是什么?

我已经按照我应该的方式包装了我的布局文件

我目前只需要视图绑定,不需要数据绑定。

【问题讨论】:

  • 我们可以这样使用Fragment(R.layout.fragment_dashboard) 吗?
  • @ShaluTD 是的,这是一种新的便捷方式,减少了编写onCreateView()方法的需要。
  • 试试我的答案,让我知道

标签: android android-viewbinding


【解决方案1】:

请更改您的fragment 如下:

class DashboardFragment : Fragment() {

    private lateinit var binding : FragmentDashboardBinding

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_dashboard, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }

}

`

【讨论】:

  • 嗨,这个DataBindingUtil来自哪里?
  • 它来自 android.databinding.DataBindingUtil。您可以改用 FragmentDashboardBinding。
  • 我根本无法访问 android.databinding.DataBindingUtil 并尝试使用 FragmentDashboardBinding 给我在主帖中显示的错误“无法访问...”
  • 导入androidx.databinding.DataBindingUtil;
  • 在 app gradle 文件中添加了dataBinding { enabled = true }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 1970-01-01
  • 2014-04-26
  • 1970-01-01
  • 2020-05-16
相关资源
最近更新 更多