You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio报错:invalid dimen与无法解析符号‘R’如何解决?

Fixing "error: invalid dimen" and "cannot resolve symbol 'R'" in Your Android Project

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:
    1. Click Build > Clean Project to delete old build files.
    2. Then click Build > Rebuild Project to generate fresh build files and the R.java file.
  • Double-check your imports: Make sure you haven't accidentally imported android.R (a system resource class) instead of your app's own R class. If you see import android.R; at the top of your .java file, delete it and replace it with import com.yourpackage.name.R; (replace com.yourpackage.name with your actual app package name).

Once you've done these steps, both errors should disappear.

内容的提问来源于stack exchange,提问作者user9488111

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:12:18