我想用键值对实现安卓标签。
目前我已经在我的代码中使用map存储了它。
我想将这些键值对的映射存储在android资源中并从资源中提取。
在选项卡上更改服务器调用必须使用存储的密钥进行。
执行此操作的最佳做法是什么。
如果键值对不是复杂对象,最好的方法是将它们存储在 SharedPreferences 中。请参考 : https://stackoverflow.com/a/7944653/1594776
如果它们很复杂,请将其存储在内部存储器中。请参考 : https://stackoverflow.com/a/7944773/1594776
如果您仍想将其存储在 xml 中,请参阅 : https://stackoverflow.com/a/10196618/1594776
解析 xml 的函数 (信用 : https://stackoverflow.com/a/29856441/1594776) :
public static Map<String, String> getHashMapResource(Context context, int hashMapResId) {
Map<String, String> map = new HashMap<>();
XmlResourceParser parser = context.getResources().getXml(hashMapResId);
String key = null, value = null;
try {
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("entry")) {
key = parser.getAttributeValue(null, "key");
if (null == key) {
parser.close();
return null;
}
}
}
else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("entry")) {
map.put(key, value);
key = null;
value = null;
}
} else if (eventType == XmlPullParser.TEXT) {
if (null != key) {
value = parser.getText();
}
}
eventType = parser.next();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return map;
}
您可以使用共享首选项来存储键值对。根据偏好,您可以以键值格式永久存储少量数据。