我刚刚下载并安装了新的Android SDK。我想创建一个简单的应用程序来测试它。

向导创建了以下代码:

package eu.mauriziopz.gps;

import android.app.Activity;
import android.os.Bundle;

public class ggps extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

但是Eclipse给出了错误

R不能被分解

在网上

setContentView(R.layout.main);

Why?

PS:我在res/layout/下有一个名为main.xml的XML文件。


当前回答

将活动添加到与包的根名称空间不同的名称空间也可能导致此错误。

例如,如果com.example.myapp是包的根名称空间,那么您可以将一个活动添加到com.example.myapp.activities名称空间。

这将产生“R不能被解决”的错误。

要修复导入,活动中默认命名空间中的R应该是:

import com.example.myapp.R;

其他回答

I would say "R can not be resolved" is something too general and can be misleading at times. I also had the same problem many times ago even when I first create a new project (which mean I did not mess with the code yet). Most of the time I just need to update my sdk manager (as some people have mentioned). But in my recent case, I found out that the path to my project file is too long (something like this E:\R&D\ANDROID\ANDROID BASIC\Folder 1\ Folder 2\..... \Folder n\MyProject). The folder names also contain spaces character. I thought it could be the case and indeed it's true, when I created a new project in another folder with shortest path possible, and none of the folders' names containing space character, it worked as normal.

每次我遇到这个错误,总是落在SO。 说到底,原因都是一样的。

所以请永远记住这张小纸条

我发现大部分时间的原因是-错误的XML布局

如果您的XML不正确,则R文件不会在 构建。

您可能需要更新/安装SDK工具。重新启动Android SDK管理器,并安装一个新项目:Android SDK Build-tools。逐个删除,修正哪一个适合你。

在我的情况下,这个错误是因为我导入了一个图像到文件夹/res,图像有一个无效的名称。真不敢相信,我花了将近一个小时来解决这个问题,直到我意识到图像有一个无效的名称:/

此外,如果你的res文件夹中有额外的文件,如“desktop.ini”,这些文件是操作系统添加的,但完全没有必要,试着删除它们。这显然是我导入项目中阻碍生成R.java的原因之一。