Java activity_main 无法解析或不是字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16584966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
activity_main cannot be resolved or not a field
提问by zamil nizar
I am a beginner in android and I was trying to make a simple application on android and this "activity_main" error is not getting cleared.I have gone through all the available answers
我是 android 的初学者,我试图在 android 上制作一个简单的应用程序,但这个“activity_main”错误没有得到清除。我已经浏览了所有可用的答案
import android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu); return true;
}
}
采纳答案by Sagar Maiyad
Clean project then try to run it. I faced the same problem. You can also do this:
清理项目然后尝试运行它。我遇到了同样的问题。你也可以这样做:
Remove from your code following imports import android.R;
or import your.application.packagename.R;
在导入后从您的代码中删除import android.R;
或import your.application.packagename.R;
Now clean the project and run it.
现在清理项目并运行它。
回答by aditya
U seem to have imported wrong R.java class
你好像导入了错误的 R.java 类
- problem is in the first line "import android.R"
- use your applications R.java class
- 问题在第一行“import android.R”
- 使用您的应用程序 R.java 类
回答by Paresh Mayani
Let me explain(put more detail) what exactly is happening with the above code.
让我解释(更详细地)上面的代码到底发生了什么。
FYI, there are two types of R.java
file exists:
仅供参考,存在两种类型的R.java
文件:
- one is your project's
R.java
file, which you would use to access resources/layout of your project. - second is Android's
R.java
file which contains ID/index of the native resources like anim, color and many more resources, which you can access by usingandroid.R.color.black
way.
- 一个是您的项目
R.java
文件,您将使用它来访问项目的资源/布局。 - 第二个是 Android 的
R.java
文件,它包含原生资源的 ID/索引,例如动画、颜色和更多资源,您可以通过使用android.R.color.black
方式访问这些资源。
Mistake:
错误:
Now, you are making mistake by importing android.R
which is not allowing you to access main_activity.xml
of your project.
现在,您通过导入android.R
不允许您访问main_activity.xml
您的项目而犯了错误。
Solution:
解决方案:
Remove android.R
and import R file of your project. You can press CTRL+ SHIFT+ Osimply, will display available options.
删除android.R
并导入项目的 R 文件。您可以简单地按CTRL+ SHIFT+ O,将显示可用选项。
回答by elplatt
Make sure you have the activity_main.xml file spelled correctly. I experienced the same problem due to having a misspelled file name.
确保您的 activity_main.xml 文件拼写正确。由于文件名拼写错误,我遇到了同样的问题。