Accessing R.java from different packages

2020-02-20 05:13发布

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?

3条回答
冷血范
2楼-- · 2020-02-20 05:51

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.

查看更多
再贱就再见
3楼-- · 2020-02-20 06:02

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
查看更多
4楼-- · 2020-02-20 06:11

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.

查看更多
登录 后发表回答