Android项目编译报错:R.java文件语法错误求助
Hey there, let's tackle this frustrating compilation error you're hitting. First off, never manually edit the R.java file—it's auto-generated by the Android build tools, so any changes you make will get overwritten, and the root of the problem is always in your project's resource files, not R.java itself.
What's Causing This?
The space between font and size in that R.java line tells me there's a syntax mistake in one of your XML resource files (like layouts, styles, or value files). For example, you might have accidentally split a single attribute into two words—something like writing android:font size="14sp" instead of the correct android:textSize="14sp", or a custom attribute named incorrectly with a space. When the build tool (aapt) tries to parse this invalid XML, it generates broken code in R.java that throws those compilation errors.
Step-by-Step Fix:
Locate the problematic resource
Look at the exact line in R.java—this line will be tied to a specific resource (like a layout ID, style, or dimension). Note the resource name, then find the corresponding XML file in yourres/directory.Fix the XML syntax error
Scan the XML file for attributes with spaces in their names. Common culprits include:- Miswritten system attributes (e.g.,
android:text Sizeinstead ofandroid:textSize) - Custom attributes with invalid spaces (e.g.,
app:font sizeinstead ofapp:fontSize) - Typos in resource names that accidentally introduce spaces
- Miswritten system attributes (e.g.,
Clean and rebuild your project
Go to Build > Clean Project to wipe old build artifacts, then Build > Rebuild Project to regenerate a correct R.java file from your fixed resources. This ensures no cached bad code is hanging around.Double-check R imports
Make sure none of your Java/Kotlin files are importingandroid.Rinstead of your project's owncom.yourpackage.R—this can cause unexpected conflicts even after fixing resources.
Example Scenario:
If your R.java error links to a TextView in activity_main.xml, you might find this broken line:
<TextView android:id="@+id/my_text" android:font size="16sp" <!-- Wrong! --> android:text="Hello World"/>
Fix it to:
<TextView android:id="@+id/my_text" android:textSize="16sp" <!-- Correct --> android:text="Hello World"/>
Once you fix the XML issue and rebuild, those R.java compilation errors should disappear.
内容的提问来源于stack exchange,提问作者pamo

