Accessing R.java from different packages

12,754

Solution 1

You can import R.file where ever you want.

import com.myname.myapp.R; 

or else use at the variable like this

com.myname.myapp.R.id.test

Solution 2

R.java is always created at the location(package) mentioned by you in the manifest file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.myname.myapp"
      android:versionCode="1"
      android:versionName="1.0">

For any other location or package , you must import R.java file from the root location.

Hope you understood the issue.

Solution 3

The warning has bearance on the fact, there are two versions of the R class. There is a generic version that comes as part of the android packages (android.R) and there is the project specific one that represents your local resource files (com.myname.myapp.R). Just see them as you would the two versions of the Date classes in the java standard library.(java.util.Date & java.sql.Date) two classes, with the same name, specified by package.

Share:
12,754
MM.
Author by

MM.

Updated on June 04, 2022

Comments

  • MM.
    MM. almost 2 years

    I have an application divided in subpackages, just for personal organization:

    com.myname.myapp
     |
     `-  com.myname.myapp.activities
     |
     `-  com.myname.myapp.whatever
     |
     `-  ...
    

    The problem is that the generated R.java is located at com.myname.myapp and thus when I type R.id.something in a class from the subpackage com.myname.myapp.activities, I get R cannot be resolved to a variable (obvious I guess).

    When I click on Organize imports (Ctrl+Shift+O), Eclipse fixes it adding import com.myname.myapp.R at the top, and everything seems to work perfectly. But on the other hand, Android documentation states this:

    Eclipse sometimes likes to add an import android.R statement at the top of your files that use resources, especially when you ask eclipse to sort or otherwise manage imports. This will cause your make to break. Look out for these erroneous import statements and delete them

    Knowing that everything is working perfectly, what should I do?

  • Haifeng Zhang
    Haifeng Zhang over 9 years
    this is the best answer!