我无法获得带有合并根标记的布局来处理视图绑定。是否可以?
include_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <include
        android:id="@+id/include_test"
        layout="@layout/merge_layout"/>
</FrameLayout>
合并布局.xml:
<?xml version="1.0" encoding="utf-8"?>
<merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/include_test">
    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="A Title"/>
</merge>
override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  val binding = IncludeLayoutBinding.inflate(layoutInflater)
  setContentView(binding.root)
  binding.includeTest.title.text = "New Title"
}
运行时异常:
java.lang.NullPointerException: Missing required view with ID: includeTest
我正在尝试将我的项目迁移到查看绑定,但在启动应用程序时出现异常。
我的主要活动包含一个 NavHostFragment,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity"
        android:orientation="vertical">
    ...
    <androidx.fragment.app.FragmentContainerView
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            app:defaultNavHost="true"
            app:navGraph="@navigation/nav_graph" />
    ...
</LinearLayout>
NavHostFragment 中默认加载的第一个片段的实现如下:
class ToolListFragment : Fragment(R.layout.fragment_tool_list) {
    ...
    private var _binding: FragmentToolListBinding? = null
    private val binding get() = _binding!!
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentToolListBinding.inflate(layoutInflater, container, false)
        return binding.root
    }
    ...
}
这是片段布局的相关部分:
<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" xmlns:app="http://schemas.android.com/apk/res-auto"
        tools:context=".ToolListFragment"
        android:orientation="vertical"
        android:background="@android:color/white">
    <com.google.android.material.tabs.TabLayout …