【发布时间】:2018-11-17 12:18:03
【问题描述】:
我最近不得不在应用的视图中添加一些单选按钮。
但是,我实际上无法编译,因为编译时出现以下错误:error: cannot find symbol variable CR 其中 CR 是新 UI 元素的 id。但是,它可以毫无问题地识别之前创建的 UI 元素(当然是在相同的布局中)。
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.02">
<RadioButton
android:id="@+id/CR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Example text" />
</RadioGroup>
此 xml 导致找不到 CR。
<EditText
android:id="@+id/Note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="@string/note"
android:textColor="@color/borderColor" />
作为比较,我可以毫无问题地找到此视图。
按顺序,这里是两个 id 的 findViewById() 调用:
RadioButton cardLeft = findViewById(R.id.CR); //leads to symbol not found
final EditText NoteField = (EditText) findViewById(R.id.Note); //works perfectly.
我还注意到 id 没有以任何方式出现在 R 中。
这是我试图解决问题的方法:
Clean Project-->Rebuild
Invalidate Caches and restart
Invalidate Caches-->clean project-->Restart
Deleted R
Checked that android.R wasn't being imported
Recreated the project and imported the code from git (and only the code, no generated files of course)
Tried changing IDs, just in case, to no avail.
Changed Settings-->Data Binding to "Reference code generated by the compiler" instead of "Reference code generated by Android Studio"
显然,对代码或设置的任何修改都会导致缓存失效和项目清理,以防万一。 进一步的测试表明我根本无法添加新的 UI 项,因为它们没有被添加到 R。
自动完成功能将新的 ID 显示为负值而不是地址。
那么,既然我已经完全没有想法了,有什么我错过的/更多未知的解决方案吗?
【问题讨论】:
-
您没有向 RadioGroup 提供 id。它属于那个组。您可以尝试查找例如:rg.findViewById(R.id.CR);
-
在发布的代码示例中我没有,对。但是,在测试时,我尝试给它一个 id 并找到它,但我仍然做不到。所以我不能按照你的建议去做。我刚刚又试了一次,是的,同样:
RadioGroup group = findViewById(R.id.Group);导致:“错误,找不到符号变量组”即使在项目清理、缓存无效并重新启动后也是如此。 -
有时只需关闭项目并重新打开它(从 Android Studio 主对话框中)即可修复 R 的错误行为。
-
是的,我也试过了,忘记添加了。另外,我认为它会在“开始一个新项目并从 github 导入”中进行介绍