26

I've wondered time and time again if there is some way to define colors in colors.xml by referencing another color that has been defined. Well, I tried it and indeed, it appears as though you can reference other colors using @color/XXX.

For example one's colors.xml could look like:

<?xml version="1.0" encoding="utf-8"?> <resources> … <color name="primary_blue">#205081</color> <color name="action_bar_text">@color/primary_blue</color> … </resources> 

But I don't want others to use my primary_blue definition directly -- it doesn't make sense to make something blue without context. The best solution I've come up with is to prefix 'direct' colors like primary_blue and then comment that they shouldn't be used directly.

Is there any way to prevent the use of these direct colors, while still allowing my colors.xml file to reference them? I'm thinking perhaps styles or an apklib could help me out.

2
  • If you going to use the same color in different situation than a "context" doesn't really make any sense. Also if the action_bar_color is accessible so will be the primary_blue color. Commented Mar 27, 2013 at 5:50
  • 1
    This would be really useful as it forces good coding practices. Too bad there isn't a way to hide the namespace in xml. Commented May 30, 2016 at 7:15

1 Answer 1

2

Adding an answer here in case anyone runs across this in the future.

When creating an Android library, you can mark resources as public. Any resource that is not in the public.xml file is assumed to be private.

Implicitly making attributes private not only prevents users of your library from experiencing code completion suggestions from internal library resources but also allows you to rename or remove private resources without breaking clients of your library. Private resources are filtered out of code completion and the theme editor, and Lint warns you when you try to reference a private resource.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.