# preferencebinder
**Repository Path**: HarmonyOS-tpc/preferencebinder
## Basic Information
- **Project Name**: preferencebinder
- **Description**: A Preferences binding library for openharmony. Using annotation processing, this library makes it easy to load Preferences values and listen for changes.
- **Primary Language**: Unknown
- **License**: Apache-2.0
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 4
- **Forks**: 1
- **Created**: 2021-04-01
- **Last Updated**: 2023-04-17
## Categories & Tags
**Categories**: harmonyos-toolkit
**Tags**: None
## README
**NOTICE:**
1.在中文路径下,Build Debug Hap(s)会失败。建议将项目放置在全英文目录下。
2.此项目中library Module类型为Java Library,下载导入后需修改/library/build.gradle中的sdk依赖路径方可正常编译。
```groovy
dependencies {
// dir改为自己本地sdk安装路径
compileOnly fileTree(dir: 'C:/Users/Administrator/AppData/Local/Huawei/Sdk/java/2.1.1.21/api', include: ['*.jar'])
}
```
# PreferenceBinder
A Preferences binding library for openharmony. Using annotation processing, this library makes it easy to load Preferences values and listen for changes.
How to Use
-------
### install
case 1:
Generate a JAR package through the library Module and add the JAR package to the libs directory.
Add the following code in entry/gradle.build.
```gradle
implementation fileTree(dir: 'libs', include: ['*.jar', '*.har'])
```
case 2:
```gradle
allprojects{
repositories{
mavenCentral()
}
}
implementation 'io.openharmony.tpc.thirdlib:preferencebinder:1.0.2'
annotationProcessor 'io.openharmony.tpc.thirdlib:preferencebinder:1.0.2'
```
#### Basic Usage
Use the `@BindPref` annotation to retrieve, initialize, and listen to changes in ("bind") preference values.
```java
public class MainAbility extends Ability {
@BindPref("my_preference_key") String valueOfPreference;
@BindPref("my_preference_key") void initializeForPreferenceValue(String valueOfPreference) {
// do something with the value
...
}
@Override public void onStart(Intent intent) {
PreferenceBinder.bind(this);
}
@Override public void onStop() {
PreferenceBinder.unbind(this);
}
}
```
As soon as `PreferenceBinder.bind()` is called, preference values are loaded from your default Preferences file and assigned to the annotated fields, and passed as the parameter to annotated methods.
Whenever the preference value changes, annotated fields are re-assigned, and annotated methods are called again with the new preference value.
Be sure to match the field types and method parameter types with the type of value stored for the preference key. This is not checked at compile time, and may cause runtime exceptions.
To use a non-default `Preferences` file, you can specify the name of the file, like so:
```java
PreferenceBinder.bind(this, "prefs_file_name");
```
#### Advanced Usage
You may specify more than one preference key when annotating methods with `@BindPref`.
In this case, the method will be called when the value for any one of the specified keys changes. For example:
```java
@BindPref({"show_full_names", "use_small_icons"})
void refreshList() {
itemProvider.notifyDataChanged()();
}
```
Method bindings with more than one preference key do not supply the new value of the preference. But if used in combination with field bindings,
the method will always be called after the new preference values have been assigned to any annotated fields so that they can be used inside the method call.
If you only want to initialize your preference values (and not bother listening for changes), you can do so with the `listen` flag. Altenatively, you can disable initialization with the `init` flag.
```java
@BindPref(value = "use_small_icons", listen = false)
void initUseSmallIcons(boolean useSmallIcons) {
// Do something with the value
// ...
}
@BindPref(value = "show_full_names", init = false)
void onShowFullNamesChanged(boolean showFullNames) {
// Do something with the value
// ...
}
```
#### Default Values
To specify default values for preference keys, use the `@PreferenceDefault` annotation on static field containing the default value, like so:
```java
@PreferenceDefault("my_preference_key") public static String MY_PREFERENCE_DEFAULT = "Unknown";
@BindPref("my_preference_key") void updateForValue(String valueOfPreference) {
// do something with the value
// ...
}
```
In the above example, `PreferenceBinder` will call `updateForValue(MY_PREFERENCE_DEFAULT)` if no value is set for `"my_preference_key"` on initialization, or if the value for the given key is removed (with "listening" enabled).
Default values apply to your entire application, so you don't need to specify them in each class. You might find it convenient to assign them all in a single utility class.
#### Widget Binding
Preference values can also be bound directly into some standard widgets.
For example, in the following code will automatically load the preference value for the key "sensitivity" and apply it to the `Slider` through its `setProgress` method.
```java
@BindPref(value = "sensitivity", bindTo = WidgetBindingType.SLIDER_PROGRESS)
Slider sensitivity;
```
In addition to loading the preference value into the widget, `PreferenceBinder` will also listen for changes to the `Slider`'s progress value (from user input) and save the new value back into your Preferences file for the given preference key!
The following table outlines the widget binding types that are currently supported. If you would like to see a binding type included in this library, please post an issue for the feature request.
"bindTo" type | Widget type | Method called | Saves user changes?
-------- | -------- | -------- | --------
ASSIGN (default) | - | = | no
ENABLED | Component | setEnabled | no
SELECTED | Component | setSelected | no
VISIBILITY | Component | setVisibility (Component.VISIBLE or Component.HIDE) | no
CHECKED | AbsButton | setChecked | yes
TEXT | Text | setText | no
SLIDER_PROGRESS | Slider | setProgressValue | yes
PROGRESS | ProgressBar | setProgressValue | no
MAX_PROGRESS | ProgressBar | setMaxValue | no
ProGuard
--------
When using ProGuard, you need to specify that generated classes should be kept, and that annotated fields and methods should not be renamed. To achieve these criteria, the following lines can be added to your ProGuard configuration:
```
-keep class me.denley.preferencebinder.** { *; }
-dontwarn me.denley.preferencebinder.internal.**
-keep class **$$PreferenceBinder { *; }
-keepclasseswithmembernames class * {
@me.denley.preferencebinder.* ;
}
-keepclasseswithmembernames class * {
@me.denley.preferencebinder.* ;
}
```
License
-------
Copyright 2015 Denley Bihari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Annotation processor structure adapted from [Butter Knife](https://github.com/JakeWharton/butterknife) (Copyright 2013 Jake Wharton).