Android Binding Library


Source link: https://github.com/txusballesteros/android-bind

Android Binding Library

This library helps to you on the process related to data binds between your model entities and your application UI, offering a bidirectional data channel.

Version

How to use

dependencies {

  ...
  compile 'com.mobandme:android-bind:1.0+' 
}

Add the library dependency to your build.gradle file.

class MyModel {

@BindTo(viewId = R.id.name)
  private String name = "Txus Ballesteros";

 ... 
}

Use @BindTo annotation on your model class fields to configure binding between your model and your UI views.

public class MainActivity extends Activity {

MyModel myModel;

ViewGroup rootView;

Binder myModelBinder;

  @Override

protected void onCreate(Bundle savedInstanceState) {

...

myModelBinder = new Binder.Builder()

.setSource(myModel)

.setDestination(rootView)

.build();

...

}

@Override

protected void onResume() {

...

//Use this code to start the data binding process.

//  In this case execute the binding between your Model Class and your app UI.

myModelBinder.bind();

//Use this code to start the reversed data binding process.

//  In this case execute the binding between your app UI and your Model Class.

myModelBinder.bindReverse();

}

  ... 
}

IMPORTANT!! Look the methods setSource and setDestination of the Binder.Builder, these methods establish the data binding direction. For example, if you set at source your Model class and set into Destination you ViewGroup, when you call to the bind method, this will be the natural direction of the data. And you will need to call bindReverse method to invert the direction of the data.

Configuring a custom Data Parser

Occasionally you will need adapt the data stored in your model to show this on your app UI or vice-versa. For example, think on a Calendar field. Well, you can create your own data parser for example to format this date before to show this on the ui.

First, create your own data parser class.

//IMPORTANT!!, don't forget extend your class from com.mobandme.android.bind.parser.DataParser class. class CalendarParser extends DataParser {

@Override
  public Object onParse(Compiler.Mapping mapping, Object value, int direction) {

Object result = value;

SimpleDateFormat dateFormatter =  new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());

 if (direction == Binder.DIRECTION_OBJECT_TO_VIEWS) {

 Calendar date = (Calendar)value;

 result = dateFormatter.format(date.getTime());

}
 else {

 try {

  Date date = dateFormatter.parse(value.toString());

  Calendar calendar = GregorianCalendar.getInstance(Locale.getDefault());

  calendar.setTime(date);

result = calendar;

  
}
 catch (ParseException error) {

 
}

}

 return result;
  
}
 
}

Second, configure your custom data parser on your model class fields. And that is all.

class MyModel {

@BindTo(viewId = R.id.dateOfBirth, parser = CalendarParser.class )
  private Calendar dateOfBirth;

... 
}

Configuring a custom Data Binder

When you use for example a custom views or a view not supported by default by the library, the you need a custom Data Binder. This class allow to manage the logic between de data and the view.

First, create your own data binder class.

//IMPORTANT!!, don't forget extend your class from com.mobandme.android.bind.binder.DataBinder class. class MyCustomViewBinder extends DataBinder {

@Override
  public void onBind(Compiler.Mapping mapping, Object object, View view, int direction) {

String value = mapping.getField()...

if (direction == Binder.DIRECTION_OBJECT_TO_VIEWS) {

 ((MyCustomView)view).setMyCustomProperty(value);

}
 else {

  mapping.getField().set(object, ((MyCustomView)view).getMyCustomProperty());

}

  
}

 ... 
}

Second, configure your custom data binder on your model class fields. And that is all.

class MyModel {

@BindTo(viewId = R.id.myCustomView, binder = MyCustomViewBinder.class )
  private Calendar dateOfBirth;

... 
}

Proguard Configuration

If you use Proguard to obfuscate your project, don't forget put this configuration into your proguard-rules.pro file.

-keep class com.mobandme.android.bind.** {
 *; 
}
 -keep class * extends com.mobandme.android.bind.parser.DataParser {
 *; 
}
 -keep class * extends com.mobandme.android.bind.parser.DataBinder {
 *; 
}
 -keep @com.mobandme.android.bind.annotations.BindableModel public class * {
 *; 
}
 -keepnames class * {

  @com.mobandme.android.bind.annotations.BindTo *;
  @com.mobandme.android.bind.annotations.Bindings *;
  @com.mobandme.android.bind.annotations.BindableModel *; 
}

IMPORTANT!!, If you use Proguard, you will need mark your model classes with @BindableModel annotation.

@BindableModel public class MyModel {

  ... 
}

License

Copyright 2015 Txus Ballesteros

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.

Resources

Simple Facebook SDK for Android which wraps original Facebook SDK.

This is a library project which makes the life much easier by coding less code for being able to login, publish feeds and open graph stories, invite friends and more.

This is an easy to use disk cache which uses DiskLruCache under the hood. The DiskLruCache is nice, but it has too low level interface for most use cases.

Library to create, read, delete, append, encrypt files and more, on internal or external disk spaces with a really simple API.

CalendarListview provides a easy way to select dates with a calendar.

A backport of the Android 4.2 GlowPadView that works on API levels 4+.

Annotation Processor to create arguments for android fragments without using reflections.

Blog entry about this library: http://hannesdorfmann.com/android/fragmentargs

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes