0

I have learned from this question that resources are globally shared in an Android Studio project.

I have a project with 3 activities (and more are coming), and I already find pretty messy to have access to every resources in any given activity.

Is there a way to allow an activity to access ids only from the associated layout ?

eg : I have MainActivity.java, activity_main.xml, Main2Activity.java, activity_main2.xml .

I would like to restrict the resources (mainly ids) accessible by MainActivity.java to activity_main.xml (so no access to resources from activity_main2.xml)

Community
  • 1
  • 1
L. Faros
  • 1,754
  • 3
  • 16
  • 35

1 Answers1

0

No there is no way to do this. You can have source and resource sets based on Build variants but cannot tie up individual activities to resource files. But why do you need it. With a good naming convention, it would be pretty easy for you to co-relate the two and a layout gets attached to an activity only you use it as an argument to the setContentViewmethod.

Dibzmania
  • 1,934
  • 1
  • 15
  • 32
  • Thank you for your answer, may I ask you to precise what you mean by "a layout gets attached to an activity only you use it as an argument to the setContentViewmethod" ? Because as you can see on the screen shot [here](http://stackoverflow.com/questions/42009108/android-studio-is-it-normal-for-r-id-to-access-every-components) I have used the setContentView method to link a layout yet it still propose me resource from an other layout. – L. Faros Feb 03 '17 at 15:30
  • Yes, that's because during the build process, all resources are assigned a numeric ID for faster access from code. Build process generates a file called `R.java` containing all resource id's. So when you refer to a resource from within your code, you will generally use `R.id.someview`. So although you can refer a resource id that is not part of your layout , you won't get a compilation error but it would fail at runtime. So there is no point to it right. I am not aware of any static compile check tool which raises a warning in the above case. – Dibzmania Feb 03 '17 at 21:35