2

I'm working on an app that will retrieve a colors.json file from server. This file will have the following structure:

[
    {"ServerActionButton.background.normal":
        { "red": 29, "green": 188, "blue": 189, "alpha":255}
    },
    {"ServerActionButton.background.disabled": 
        { "red": 164, "green": 228, "blue": 229, "alpha":255}
    },
    {"ServerActionButton.title.normal": 
        { "red": 255, "green": 255, "blue": 255, "alpha":255}
    },
    ...
]

This JSON should be retrieved on app startup, and I should be able to use these colors throughout the whole app.

Question: What's the best way to do this? I've thought about the following options:

  • Generating a resource XML file from the JSON (it would be great, but is it possible?).
  • Mapping the JSON to a model, and then storing it in SharedPreferences.
  • Building a local database with the data retrieved from the JSON.

Which would be the best approach? Is there some other possibility I'm not considering?

Thanks in advance!

Nadia Castelli
  • 147
  • 2
  • 11

1 Answers1

0

Consider a more hierarchical structure:

[
    {
        "item" : "ServerActionButton",
        "styles" : {
            "normal" :
                          {
                             "title" :      "#FFFFFFFF",
                             "background" : "#FF1DBCBD"
                          },

             "disabled" : {
                             "title" :      "#FF7F7F7F",
                             "background" : "#FF1DBCBD"
                          }
         }
    },

    ...
]

Then that's easily parsed into a map (or a map of maps)

class StyleProperties
{
    public Color title;
    public Color background;
}



HashMap<String, HashMap<String, StyleProperties>> stylemappings = YourFunctionToParseTheJson(strJson);

And then you can easily apply styles to elements as follows:

void ApplyStylesToView(View v, String item, String style)
{
    StyleProperty styleProp = null;

     HashMap<String, StyleProperties> stylePropertiesForItem = stylemappings.get("item");

     if (stylePropertiesForItem != null)
     {
          styleProp = stylePropertiesForItem.get(style);

          v.setBackgroundColor(styleProp.background);

          // if the item is a textview, apply the title color
          TextView tv = v as TextView;
          if (v instanceof TextView)
          {
              ((TextView)v).setTextColor(styleProp.title);
          }
     }
}
selbie
  • 100,020
  • 15
  • 103
  • 173