简体   繁体   中英

R.java file in Android Studio

I'm doing my first projects with Android Studio and I've found that I get an error with the R.java file, because in every class when I make a reference to R.id.X it turns red and it says that it cannot resolve the symbol R..does anyone can help me with this?

在此处输入图片说明

It happens often with everyone when trying to import a project or opening previous projects....It's not a programming error and it can be fixed easily... This always works for me...

- Build->Clean Project
- Build-> Rebuild Projects
- File-> Invalidate Caches/ Restart

There are several probability that make the error happens:

  1. Error in xml code When we have a wrong open or close tag in XML or wrong attribute in a resource like layout , strings.xml , AndroidManifest.xml , etc, it will makes the error for R.java. So, you need to fix them to resolve the error.

  2. Using invalid name in drawable Sometimes we face this error:

    Invalid file name: must contain only [a-z0-9_.]

    It means that we have an invalid name for drawable like MyDrawable.png . Change it to mydrawable.png or my_drawable.png or any string with character from a to z and 0 to 9 and a _ .

  3. Using the wrong package name for import in java code. This is usually happens when we refactoring the app package name but forget to change the package name in AndroidManifest.xml . For example, if we have a package name com.example.project we should have the same package name in AndroidManifest.xml. Something like this:

     <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.project"> ... </manifest> 

    Then, we need to import the R.java with import com.example.project.R;

  4. Using already removed custom view library. When we previously using a custom view and currently don't want to use it anymore, we usually delete the dependency from the build.gradle. But we accidentally forget to remove the custom view in our layout. So, check the view before removing the custom view dependency.

After resolving one of the problems above, we can clear and rebuild the project. If the problem still persist, then use the last resort. Use File-> Invalidate Caches/ Restart... from Android Studio menu.

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