简体   繁体   中英

activity_main cannot be resolved or not a field

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

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;
  }
}

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;

Now clean the project and run it.

Let me explain(put more detail) what exactly is happening with the above code.

FYI, there are two types of R.java file exists:

  1. one is your project's R.java file, which you would use to access resources/layout of your project.
  2. 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 using android.R.color.black way.

Mistake:

Now, you are making mistake by importing android.R which is not allowing you to access main_activity.xml of your project.

Solution:

Remove android.R and import R file of your project. You can press CTRL + SHIFT + O simply, will display available options.

U seem to have imported wrong R.java class

  • problem is in the first line "import android.R"
  • use your applications R.java class

Make sure you have the activity_main.xml file spelled correctly. I experienced the same problem due to having a misspelled file name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM