我是 Android 导航组件的新手,我想我已经准备好使用它了,但是当我尝试使用操作或片段 ID 导航到另一个片段时,导航图 xml 文件中生成的 ID 未在 R 中列出.id,所以我无法使用它们进行导航。
这是我要执行的代码:
view.findNavController().navigate(R.id.action_mainFragment_to_addFragment)
这是我的 nav_graph.xml 文件(自动生成):
<navigation 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/nav_graph"
app:startDestination="@id/mainFragment">
<fragment android:id="@+id/mainFragment"
android:name="com.example.nopesal.costlist.MainFragment"
android:label="MainFragment"
tools:layout="@layout/fragment_main">
<action android:id="@+id/action_mainFragment_to_addFragment" app:destination="@id/addFragment"
app:enterAnim="@anim/nav_default_enter_anim" app:exitAnim="@anim/nav_default_exit_anim"
app:popEnterAnim="@anim/nav_default_pop_enter_anim" app:popExitAnim="@anim/nav_default_pop_exit_anim"/>
</fragment>
<fragment android:id="@+id/addFragment" android:name="com.example.nopesal.costlist.AddFragment"
android:label="fragment_add" tools:layout="@layout/fragment_add"/>
</navigation>
如您所见,ID 是使用
@+id/
生成的,当我尝试引用它们时它应该出现在 R.id 中,但它们没有显示。如果我尝试引用一个动作或片段并不重要,两者都没有显示。
我尝试过清理项目、重建、更改 gradle 导航实现、更改 id 名称、重启 Android Studio...我无法解决。还搜索教程,使用 R.id 是他引用它们的唯一方法,所以我不知道我做错了什么。
如果有人遇到同样的问题或知道解决方案,我将不胜感激。 非常感谢。
我刚刚解决了!
我刚刚注意到我在文件的开头有这个导入。我想他们在复制并粘贴导航代码后会自动导入。删除这个导入解决了这个问题。
import android.R.attr.data
import android.R
如果你使用android模块化架构,确保正确导入
.R
例子:
com.example.feature_camera.R