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

Android Data Binding

Android Data Binding

Speaking about common features of Android Data Binding support library (http://developer.android.com/tools/data-binding/guide.html).

2aec47eb9a940c619f05972f0db5aa00?s=128

Kirill Rozov

November 12, 2015
Tweet

Transcript

  1. Android Data Binding

  2. public class AndroidVersion {
 
 private final String mName;
 private

    final String mNumber;
 
 public AndroidVersion(String name, String number) {
 mName = name;
 mNumber = number;
 }
 
 public String getNumber() { return mNumber; }
 public String getName() { return mName; }
 }
  3. <LinearLayout
 style="@style/AndroidVersion.Root"
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 >
 
 <TextView
 android:id="@+id/name"


    style="@style/AndroidVersion.Name"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 />
 
 <TextView
 android:id="@+id/number"
 style="@style/AndroidVersion.Number"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 />
 
 </LinearLayout>
  4. public class VersionViewHolder extends RecyclerView.ViewHolder {
 
 public final TextView

    name;
 public final TextView number;
 
 public VersionViewHolder(View itemView) {
 super(itemView);
 name = (TextView) itemView.findViewById(R.id.name);
 number = (TextView) itemView.findViewById(R.id.number);
 }
 
 public void setVersion(AndroidVersion version) {
 name.setText(version.getName());
 number.setText(version.getNumber());
 }
 }
  5. <layout xmlns:android="http://schemas.android.com/apk/res/android">
 
 <data>
 <variable name="version" type=“com.exposit.databindingsample.AndroidVersion" />
 </data>
 


    <LinearLayout
 style="@style/AndroidVersion.Root"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 >
 
 <TextView
 android:id="@+id/name"
 style="@style/AndroidVersion.Name"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="@{version.name}"
 />
 
 <TextView
 android:id="@+id/number"
 style="@style/AndroidVersion.Number"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="@{version.number}"
 />
 
 </LinearLayout>
 </layout>
  6. <layout xmlns:android="http://schemas.android.com/apk/res/android">
 
 <data>
 <variable name="version" type=“com.exposit.databindingsample.AndroidVersion" />
 </data>
 


    <LinearLayout
 style="@style/AndroidVersion.Root"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 >
 
 <TextView
 android:id="@+id/name"
 style="@style/AndroidVersion.Name"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="@{version.name}"
 />
 
 <TextView
 android:id="@+id/number"
 style="@style/AndroidVersion.Number"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="@{version.number}"
 />
 
 </LinearLayout>
 </layout>
  7. <layout xmlns:android="http://schemas.android.com/apk/res/android">
 
 <data>
 <variable name="version" type=“com.exposit.databindingsample.AndroidVersion" />
 </data>
 


    <LinearLayout
 style="@style/AndroidVersion.Root"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 >
 
 <TextView
 android:id="@+id/name"
 style="@style/AndroidVersion.Name"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="@{version.name}"
 />
 
 <TextView
 android:id="@+id/number"
 style="@style/AndroidVersion.Number"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="@{version.number}"
 />
 
 </LinearLayout>
 </layout>
  8. public class VersionBindingViewHolder extends RecyclerView.ViewHolder {
 
 private final ItemVersionBinding

    mBinding;
 
 public VersionBindingViewHolder(View itemView) {
 super(itemView);
 mBinding = ItemVersionBinding.bind(itemView);
 }
 
 public void setVersion(AndroidVersion version) {
 mBinding.setVersion(version);
 }
 }
  9. <data>

  10. <layout xmlns:android="http://schemas.android.com/apk/res/android">
 
 <data>
 <import type="com.exposit.databindingsample.MyStringUtils" />
 <variable name="version"
 type="com.exposit.databindingsample.AndroidVersion"

    />
 </data>
 
 <TextView
 android:id="@+id/name"
 …
 android:text="@{MyStringUtils.toLowerCase(version.name)}"
 />
 </layout> Type import
  11. 
 <data>
 <import type="android.graphics.drawable.Drawable" />
 <variable name="user" type="com.example.User" />
 <variable

    name="image" type="Drawable" />
 <variable name="note" type="String" />
 </data>
 Variables
  12. <data>
 <import type="com.exposit.databindingsample.View"
 alias="CustomView" />
 </data> Type alias

  13. Expression language

  14. • Математические операторы • Конкатенация строк • Логические операторы •

    Бинарные операторы • Унарные операторы • Битовые сдвиги • Операторы сравнения • instanceof • Литералы: строковые, числовые, символьные, null • Приведения типа • Вызов методов и доступ к полям • Доступ к элементам массива, List, Sparse List и Map через оператор [] • Тернарный оператор ?: Поддерживаемые операторы
  15. Неподдерживаемые операторы • this • super • new • Явное

    выполнение типизированных методов
 ( Sample.<String>method() )
  16. Null Coalescing Operator android:text="@{user.displayName ?? user.lastName}" android:text="@{user.displayName ?? user.lastName}"

  17. Null Coalescing Operator android:text="@{user.displayName ?? user.lastName}" android:text="@{user.displayName != null ?

    user.displayName : user.lastName}"
  18. Null safety Код, сгенерированный библиотекой Data Binding, автоматом проверяет на

    null все объекты и предотвращает NullPoinerException. Например, если в выражение @{version.name} version является null, значение version.name будет являться его значение по умолчанию - null. Если поле или метод будут возвращать примитивный тип данных, то будет использовано значение этого типа по умолчанию.
  19. Ресурсы

  20. android:padding="@{@dimen/largePadding}" Dimension resources

  21. android:text="@{@string/nameFormat(firstName, lastName)}" String format resources

  22. android:text="@{@plurals/banana(bananaCount)}" Plurals resources

  23. Type Normal Reference Expression Reference String[] @array @stringArray int[] @array

    @intArray TypedArray @array @typedArray Animator @animator @animator StateListAnimator @animator @stateListAnimator color (int) @color @color ColorStateList @color @colorStateList
  24. Обработка событий

  25. public class VersionEventsHandler {
 
 private final VersionBindingViewHolder mViewHolder;
 


    public VersionEventsHandler(
 VersionBindingViewHolder viewHolder) {
 mViewHolder = viewHolder;
 }
 
 public void onVersionClicked(View view) {…}
 }
  26. public class VersionBindingViewHolder extends RecyclerView.ViewHolder {
 
 private final ItemVersionBinding

    mBinding;
 
 public VersionBindingViewHolder(View itemView) {
 super(itemView);
 mBinding = ItemVersionBinding.bind(itemView);
 mBinding.setHandler(new VersionEventsHandler() {
 public void onVersionClicked(View view) {…}
 });
 }
 
 public void setVersion(@NonNull AndroidVersion version) {
 mBinding.setVersion(version);
 }
 }
  27. <layout xmlns:android="http://schemas.android.com/apk/res/android">
 
 <data>
 <variable name="version"
 type=“com.exposit.databindingsample.AndroidVersion" />
 <variable name=“handler"


    type=“com.exposit.databindingsample.VersionEventsHandler" />
 </data>
 
 <View
 …
 android:onClick="@{handler.onVersionClicked}"
 />
 </layout>
  28. Data objects

  29. Observable Object public class AndroidVersion extends BaseObservable {
 
 private

    String mName;
 private String mNumber;
 
 public AndroidVersion(String name, String number) {
 mName = name;
 mNumber = number;
 }
 
 @Bindable public String getNumber() { return mNumber; }
 
 @Bindable public String getName() { return mName; }
 
 public void setName(String name) {
 mName = name;
 notifyPropertyChanged(BR.name);
 }
 
 public void setNumber(String number) {
 mNumber = number;
 notifyPropertyChanged(BR.number);
 }
 }
  30. Observable Fields public class AndroidVersion {
 
 public final ObservableField<String>

    name;
 public final ObservableField<String> number;
 
 public AndroidVersion(String name, String number) {
 this.name = new ObservableField<>(name);
 this.number = new ObservableField<>(number);
 }
 }
  31. Observable Collections • ObservableArrayList<T> • ObservableMap<K, V> • ObservableArrayMap<K, V>

  32. Attribute setters

  33. Automatic Setters <layout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:bind="http://schemas.android.com/apk/res-auto"
 > <android.support.v4.widget.DrawerLayout android:layout_width="wrap_content" android:layout_height="wrap_content" bind:scrimColor="@{@color/scrim}"

    bind:drawerListener=“@{activity.drawerListener}”/> <layout/>
  34. Renamed Setters @BindingMethods({ @BindingMethod( type = "android.widget.ImageView", attribute = "android:tint",

    method = "setImageTintList"), })
  35. Custom attributes

  36. public class TypefaceTextView extends TextView {
 
 public TypefaceTextView(Context context)

    { super(context);}
 
 public TypefaceTextView(Context context, AttributeSet attrs) {
 super(context, attrs);
 init(context, attrs, 0);
 }
 
 public TypefaceTextView(Context context, AttributeSet attrs, int defStyleAttr) {
 super(context, attrs, defStyleAttr);
 init(context, attrs, defStyleAttr);
 }
 
 private void init(Context context, AttributeSet attrs, int defStyleAttr) {
 TypedArray attrsArray =
 context.obtainStyledAttributes(attrs, R.styleable.TypefaceTextView, defStyleAttr, 0);
 String font = attrsArray.getString(R.styleable.TypefaceTextView_font);
 attrsArray.recycle();
 
 if (font != null) {
 AssetManager assets = context.getAssets();
 setTypeface(Typeface.createFromAsset(assets, "fonts/" + font + ".ttf"));
 }
 }
 }
  37. <LinearLayout
 style="@style/AndroidVersion.Root"
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 …
 >
 
 <com.exposit.databindingsample.TypefaceTextView
 …
 app:font="Roboto-Medium"


    />
 
 <com.exposit.databindingsample.TypefaceTextView
 …
 app:font="Roboto-Italic"
 />
 
 </LinearLayout>
  38. @BindingAdapter("bind:font")
 public static void setFont(TextView textView, String font) {
 AssetManager

    assets = textView.getContext().getAssets();
 String fontPath = "fonts/" + font + ".ttf"
 Typeface typeface = Typeface.createFromAsset(assets, fontPath);
 textView.setTypeface(typeface);
 }
  39. <layout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:bind="http://schemas.android.com/apk/res-auto"
 >
 
 <LinearLayout>
 
 <TextView
 …
 bind:font="@{"Roboto-Medium"}"


    />
 
 <TextView
 …
 bind:font="@{`Roboto-Italic`}"
 />
 
 </LinearLayout>
 </layout>
  40. @BindingAdapter({"bind:imageUrl", "bind:errorDrawable"})
 public static void loadImage(
 ImageView imageView, String imageUrl,

    Drawable error) {
 Picasso.with(imageView.getContext())
 .load(imageUrl)
 .error(error)
 .into(imageView);
 }
  41. <layout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:bind="http://schemas.android.com/apk/res-auto"
 >
 
 <ImageView
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 bind:imageUrl=“@{`http://exposit-ds.com/logo.png`}”
 bind:errorDrawable="@{@drawable/error}"


    />
 
 </layout>
  42. <layout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:bind="http://schemas.android.com/apk/res-auto"
 >
 
 <ImageView
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 bind:errorDrawable="@{@color/error}"
 bind:imageUrl=“@{`sample_image_url`}”


    />
 
 </layout>
  43. @BindingConversion
 public static ColorDrawable colorToDrawable(int color) {
 return new ColorDrawable(color);


    } Binding conversion