Dart


Source link: https://github.com/f2prateek/dart

Dart

Extra "binding" library for Android which uses annotation processing to generate code that does direct field assignment of your extras.

Dart is inspired by ButterKnife.

class ExampleActivity extends Activity {

@InjectExtra String extra1;
@InjectExtra int extra2;
@InjectExtra User extra3; // User implements Parcelable
 @Override public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.simple_activity);

  Dart.bind(this);

  // TODO Use "bound" extras...

}
 
}

Simply call one of the bind() methods, which will delegate to generated code. You can bind from an Activity (which uses its intent extras), Fragment (which uses its arguments) or directly from a Bundle.

The key used for the extra will be the field name by default. However, it can be set manually as a parameter in the annotation: @InjectExtra("key")

Optional Injection

By default all @InjectExtra fields are required. An exception will be thrown if the target extra cannot be found.

To suppress this behavior and create an optional binding, add the @Nullable annotation to the field or method. Any annotation with the class name Nullable is respected, including ones from the support library annotations and ButterKnife.

@Nullable @InjectExtra String title;

Default Values

You can assign any values to your fields to be used as default values, just as you would in regular "binding"-free code.

@InjectExtra String title = "Default Title";

This value will be overridden after you call bind(). Remember to use the @Nullable annotation, if this binding is optional.

Bonus

Also included is a get() method that simplifies code to retrieve extras from a Bundle. It uses generics to infer return type and automatically perform the cast.

Bundle bundle = getIntent().getExtras();
 // getArguments() for a Fragment User user = Dart.get(bundle, "key");
 // User implements Parcelable

Henson

In Dart 2.0, we added an annotation processor that helps you to navigate between activities. The new module is called Henson (after Matthew Henson, the African-American Arctic explorer that first reached the North Pole) :

For the sample activity mentioned above, Henson will offer a DSL to navigate to it easily :

Intent intent = Henson.with(this)

.gotoExampleActivity()

.extra1("defaultKeyExtra")

.extra2(2)

.extra3(new User())

.build();
  startActivity(intent);

Of course, you can add any additional extra to the intent before using it.

The DSL will be generated for all classes which contain @InjectExtra fields. If you want to extend it to other classes, use the @HensonNavigable annotation.

@HensonNavigable class AnotherActivity extends Activity {

@Override public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  ...

}
 
}

The Henson annotation processor will generate the Henson navigator class (used above) in a package that is :

  • either the package specified by the dart.henson.package annotation processor option
  • or if no such option is used, in the common package of all annotated activities. See the Javadoc of HensonExtraProcessor for more details.

If your activites and fragment are in different packages, you will need to specify a package via the dart.henson.package annotation processor option. If you're using gradle, simply add this to your build.gradle

apt {

  arguments {

"dart.henson.package" "your.package.name"
  
}
 
}

If you're using the newest version of Android gradle plugin, it's now possible to use a built-in annotationProcessor scope instead of apt. In this case, you can pass arguments to the annotation processors using :

defaultConfig {

  javaCompileOptions {

annotationProcessorOptions {

 arguments = [ 'dart.henson.package' : 'your.package.name' ]

}

  
}
 
}

Bonus

As you can see from the examples above, using both Dart & Henson not only provides a very structured generated navigation layer and convenient DSLs; it also allows to wrap/unwrap parcelables automatically.

Parceler

Dart 2.0 offers a built-in support for Parceler. Using Parceler with Dart 2 is optional.

If you use Parceler, Dart will automatically detect @Parcel annotated beans (pojos), or collections of them, and wrap them using the Henson DSL and unwrap them when they are bound via Dart.

@Parcel public class ParcelExample {

  ... 
}
class OneMoreActivityActivity extends Activity {

@InjectExtra ParcelExample extra;
 @Override public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.simple_activity);

  Dart.bind(this);

  // TODO Use "bound" extras...

}
 
}
Intent intent = Henson.with(this)

.gotoOneMoreActivityActivity()

.extra(new ParcelExample())

.build();
  startActivity(intent);

Parceler usage is optional and will take place only when Parceler is present in the classpath.

When available, Parceler will be used to parcelize collections instead of serializing them, in order to gain speed.

ProGuard

If ProGuard is enabled be sure to add these rules to your configuration:

-dontwarn com.f2prateek.dart.internal.** -keep class **__ExtraBinder {
 *; 
}
 -keepclasseswithmembernames class * {

  @com.f2prateek.dart.* <fields>; 
}
 #for dart 2.0 only -keep class **Henson {
 *; 
}
 -keep class **$$IntentBuilder {
 *; 
}

#if you use it #see Parceler's github page #for specific proguard instructions 

Download

For Dart 2.x : Gradle:

compile 'com.f2prateek.dart:dart:(insert latest version)' provided 'com.f2prateek.dart:dart-processor:(insert latest version)'

or maven

<dependency>
<groupId>com.f2prateek.dart</groupId>
<artifactId>dart</artifactId>
<version>(insert latest version)</version> </dependency> <dependency>
<groupId>com.f2prateek.dart</groupId>
<artifactId>dart-processor</artifactId>
<version>(insert latest version)</version>
<scope>provided</scope> </dependency>

And for using Henson : Gradle:

compile 'com.f2prateek.dart:henson:(insert latest version)' provided 'com.f2prateek.dart:henson-processor:(insert latest version)'

When using Henson, as Android Studio doesn't call live annotation processors when editing a file, you might prefer using the apt Android Studio plugin. It will allow you to use the Henson generated DSL right away when you edit your code.

The Henson annotation processor dependency would then have to be declared within the apt scope instead of provided.

or maven

<dependency>
<groupId>com.f2prateek.dart</groupId>
<artifactId>henson</artifactId>
<version>(insert latest version)</version> </dependency> <dependency>
<groupId>com.f2prateek.dart</groupId>
<artifactId>henson-processor</artifactId>
<version>(insert latest version)</version>
<scope>provided</scope> </dependency>

For Dart 1.x : Gradle:

compile 'com.f2prateek.dart:dart:(insert latest version)'

Maven:

<dependency>
<groupId>com.f2prateek.dart</groupId>
<artifactId>dart</artifactId>
<version>(insert latest version)</version> </dependency>

Kotlin

For all Kotlin enthusiasts, you may wonder how to use this library to configure your intents. This is perfectly compatible, with a bit of understanding of how Kotlin works, especially when it comes to annotation processing.

Assuming that your project is already configured with Kotlin, update your build.gradle file :

apply plugin: 'kotlin-kapt'  dependencies {

implementation 'com.f2prateek.dart:henson:(insert latest version)'
kapt 'com.f2prateek.dart:henson-processor:(insert latest version)' 
}

Now you can use @InjectExtra annotation to generate either non-null or nullables properties :

class ExampleActivity : Activity() {

@InjectExtra
lateinit var title: String
 @InjectExtra
var titleDefaultValue: String = "Default Title"
 @Nullable
@JvmField
@InjectExtra
var titleNullable: String? = null
 override fun onCreate(savedInstanceState: Bundle?) {

 super.onCreate(savedInstanceState)

 setContentView(R.layout.simple_activity)

 Dart.inject(this)

 // TODO Use "injected" extras...

}
 
}

Note that you still need to use the Java @Nullable annotation otherwise Henson won't interpret your property as nullable and will generate a builder with a mandatory field (even though you declared your property as nullable with the "?" Kotlin marker). Finally, you have to add the @JvmField annotation or your compiler will complain about not having a backing field.

You may need to add an argument to your build.gradle file if your activities and fragments are located in different packages as mentioned above. The Kotlin syntax with kapt is :

kapt {

  arguments {

arg("dart.henson.package", "your.package.name")
  
}
 
}

Finally, if you are using Parceler that comes built-in with this library, the syntax does not change from Java, except when dealing with data classes. Because Parceler requires a default constructor with no argument, here is how you need to declare your data class :

@Parcel(Parcel.Serialization.BEAN) data class ParcelExample @ParcelConstructor constructor(

val id: Int,

val name: String,

... 
}

Talks & Slides

License

Copyright 2013 Jake Wharton Copyright 2014 Prateek Srivastava (@f2prateek)  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

Font Awesome gives you scalable vector icons that can instantly be customized - size, color, drop shadow, and anything that can be done with the power of CSS.

Forecast / DarkSky's Skycons, Animated Weather icons recreated for Android.

Demo application

material-design-icons are the official open-source icons featured in the Google Material Design specification.

What's included?

  • SVG versions of all icons in both 24px and 48px flavours
  • SVG and CSS sprites of all icons
  • 1x, 2x icons targeted at the Web (PNG)
  • 1x, 2x, 3x icons targeted at iOS (PNG)
  • Hi-dpi versions of all icons (hdpi, mdpi, xhdpi, xxhdpi, xxxhdpi) (PNG)

Sick of writing ViewHolder classes, inflate xml and distinguish ViewTypes in your adapters?

Write less code with AnnotatedAdapter, an annotation processor for generating RecyclerView and AbsListView adapters.

Make Android screenshots of scrollable screen content.

This tool makes a number of screenshots, scrolling screen content by half height each time. Status bar and navigation bar are included only once.

A beautiful Android custom View that works similar to a range or seek bar. Selection by gesture. With animations. Supporting API level 11+.

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