How to make Android library resources private?

后端 未结 2 1001
無奈伤痛
無奈伤痛 2021-02-13 09:46

How do I make the resources (string, dimen, color, etc.) in my Android library module private?

I\'ve tried both documented ways of doing this and neither work...

相关标签:
2条回答
  • 2021-02-13 09:56

    Your resources are assumed to be public in any module (library, etc) unless you start, explicitly, declaring any resource in the module to be public. At that point you basically opt-in to every resource (within the module) being private except what you mark as public. This preserves backward compatibility and let's you incrementally tighten down access in large projects with many modules.

    To make all resources private simply add <public /> to any of your existing resource files.

    The above answer talks about adding a specific resource directory just to manage the public/private modifiers. While that works, I might suggest you manage the visibility and declaration in the main resource files next to where they are declared. Here's a sample strings.xml resource file I used with a brand new library module. The public/private prefix in the string names is for illustrative purposes only.

    res/values/strings.xml

    <resources>
      <string name="app_name">My Library2</string>
    
      <public type="string" name="public_string_in_lib2" />
      <string name="public_string_in_lib2">public string in lib2</string>
    
      <string name="private_string_in_lib2">private string in lib2</string>
    </resources>
    

    Fundamentally, these qualifications are being used to create a public.txt file that is embedded in the AAR that will be depended upon by another module. Various pieces of tooling like Android Studio will use this information to flag/warn, but technically, a consumer of the library isn't prevented from using the resource unless their tooling is being really strict.

    0 讨论(0)
  • 2021-02-13 10:21

    Option #2 actually works. I had not properly defined my sourceSets in my build.gradle...

    sourceSets {
        main.res.srcDirs = [
            'src/main/res',
            'src/main/res-public'
        ]
    }
    
    0 讨论(0)
提交回复
热议问题