Android Studio报错:invalid dimen与无法解析符号‘R’如何解决?
Hey there! Let's tackle these issues one by one—they're linked, so fixing the first will resolve the second.
1. Fix the "error: invalid dimen" in dimens.xml
The root problem is your dimens.xml file: you've set the value of each <dimen> tag to the same string as its name attribute, but Android expects a valid dimension value with a unit (like dp, sp, px, etc.).
Your current code:
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="activity_vertical_margin">activity_vertical_margin</dimen> <dimen name="activity_horizontal_margin">activity_horizontal_margin</dimen> </resources>
Replace it with this correct version (using 16dp as a common margin value—you can adjust the number to your needs):
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="activity_vertical_margin">16dp</dimen> <dimen name="activity_horizontal_margin">16dp</dimen> </resources>
Why this works: Dimen resources require a numerical value paired with a dimension unit (dp for layout spacing, sp for text size). The string you had before isn't a valid dimension, so the compiler throws the "invalid dimen" error.
2. Resolve "cannot resolve symbol 'R'"
The "cannot resolve symbol 'R'" error almost always happens because Android Studio can't generate the R.java file (which maps your resources to code) when there's a mistake in your resource files (like the invalid dimen above). Now that you've fixed dimens.xml, follow these steps:
- First, sync your project with Gradle: Go to
File > Sync Project with Gradle Files(this ensures Gradle picks up the fixed resource file). - If syncing alone doesn't work, clean and rebuild the project:
- Click
Build > Clean Projectto delete old build files. - Then click
Build > Rebuild Projectto generate fresh build files and theR.javafile.
- Click
- Double-check your imports: Make sure you haven't accidentally imported
android.R(a system resource class) instead of your app's ownRclass. If you seeimport android.R;at the top of your.javafile, delete it and replace it withimport com.yourpackage.name.R;(replacecom.yourpackage.namewith your actual app package name).
Once you've done these steps, both errors should disappear.
内容的提问来源于stack exchange,提问作者user9488111

