By using the powerful of annotation processor, we can reduce tons of code on getting and saving Preference. Everything will come up with simple get/set function.
AnnoPref provides:
- Automatically generate
get/set/has
function for each preference field - "AntiHack" by encoding the key of each preference field name
- Customizable the name of each field (no effect if AntiHack is on)
- Simple create
static
get/set functions or inside asingleton
for Dependencies Injection
@Preference
public class Foo {
private int baz;
}
will be generated to
public class FooPref {
public static int getBaz() {
...
}
public static int getBaz(int defaultValue) {
...
}
public static void setBaz(int intPref) {
...
}
public static boolean hasBaz() {
...
}
}
compile 'com.tuanchauict.annopref:annopref:1.0.0'
annotationProcessor 'com.tuanchauict.annopref:annopref-compiler:1.0.0'
In Application's onCreate
:
AnnoPref.init(getSharedPreferences("name", MODE_PRIVATE));
@Preference
class Foo{
int foo;
String baz;
}
We will have these fields in the preference file:
foo
baz
@Preference
attributes
prefix
: the prefix for each field in the classautoPrefix=true
: will use class name (include package name) be the prefix of the field namesantiHack=true
: will hash the field's name by using MD5 and Base64type
:STATIC
: create static methodsSINGLETON
: create concrete methods of object and agetInstance()
static function
@Field
value
: custom the name of field (can be shortened by@Field("a-key-name")
@Ignore
Add this annotation on a field if we don't want this be generated to preference.
//TODO default value
In Java code, for get/set field Foo.baz in SharePreferences, just call:
FooPref.getBaz(); //or
FooPref.getBaz(defaultValue);
//and
FooPref.setBaz();
FooPref.hasBaz();
- boolean
- int
- long
- float
- String
- List<Integer>
- List<Long>
- List<Float>
- List<String>
- Set<Integer>
- Set<Long>
- Set<String>
- More types:
- Array
ListSet- Map
- Object (json)
Default value- Get rid of
autoPrefix
attribute