Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Data Binding and You

Data Binding and You

Lightning talk overview of data binding on Android. Presented at Airbnb's Taking Flight, May 31st, San Francisco, CA.

Siena Aguayo

May 31, 2016

More Decks by Siena Aguayo

Other Decks in Technology


  1. @sienatime Attaches model data to your view public class Pikachu

    { public String name = "Pikachu"; public String genus = "Mouse"; public String type = "Electric"; public int imageResource = R.drawable.sprite_25; }
  2. @sienatime Eliminate boilerplate! TextView pokeName = (TextView) findViewById(R.id.poke_name); TextView pokeGenus

    = (TextView) findViewById(R.id.poke_genus); TextView pokeType = (TextView) findViewById(R.id.poke_type); pokeName.setText(pikachu.name); pokeGenus.setText(String.format(R.string.genus_format, pikachu.genus)); pokeType.setText(pikachu.type) PikachuActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.pikachu_activity); binding.setPikachu(new Pikachu());
  3. @sienatime Usage in build.gradle android { dataBinding { enabled =

    true } } dependencies { compile "com.android.support:appcompat-v7:23.4.0" }
  4. @sienatime Usage in XML <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="pikachu" type="net.emojiparty.databindingexample.Pikachu"/>

    </data> <LinearLayout> <TextView ... android:text="@{pikachu.name}"/> <TextView ... android:text="@{@string/genus_format(pikachu.genus)}"/> <TextView ... android:text="@{pikachu.type}"/> </LinearLayout> </layout>
  5. @sienatime Custom @BindingAdapter XML <ImageView ... android:imageResource= "@{pikachu.imageResource}"/> ImageViewBindings.java @BindingAdapter("android:imageResource")

    public static void setImage(ImageView view, int resourceId) { view.setImageDrawable(view.getContext().getDrawable(resourceId)); } Pikachu.java public int imageResource = R.drawable.sprite_25;
  6. @sienatime Further Reading • Code used in this presentation https://github.com/sienatime/pikachu-data-

    binding • Official documentation https://developer.android.com/topic/libraries/data- binding/index.html • “Data Binding Techniques” by Jacob Tabak’s (video from Droidcon NYC 2015) https://www.youtube.com/watch?v=WdUbXWztKNY • “Marshmallow Brings Data Bindings to Android” by Yiğit Boyar and George Mount (video and transcription from Bay Area Android Dev Group, Oct. 2015) https://realm.io/news/data-binding-android-boyar-mount/ • “Advanced Data Binding” by Yiğit Boyar (video from Google I/O 2016) https: //www.youtube.com/watch?v=DAmMN7m3wLU