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

Building Android Apps using MVVM and Data Binding

Building Android Apps using MVVM and Data Binding

Introductory talk about how to use the Android Data Binding library to create Android apps presented during GDG SBA DevFest 2016.

Mohamed Guendouz

November 12, 2016
Tweet

More Decks by Mohamed Guendouz

Other Decks in Programming

Transcript

  1. Old Way private TextView tvFirstName; private TextView tvLastName; @Override protected

    void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvFirstName = (TextView) findViewById(R.id.tv_firstname); tvLastName = (TextView) findViewById(R.id.tv_lastname); } private void updateUser(User user) { if (user != null) { tvFirstName.setText(user.getFirstName()); tvLastName.setText(user.getLastName()); } } Declare view variables Null Check Set firstname and lastanem separatly findViewById()
  2. Injection Way: ButterKnife @BindView(R.id.tv_firstname) TextView tvFirstName; @BindView(R.id.tv_lastname) TextView tvLastName; @Override

    protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); } private void updateUser(User user) { if (user != null) { tvFirstName.setText(user.getFirstName()); tvLastName.setText(user.getLastName()); } } Bind views to variables using @BindView annotation Bind layout to Activity
  3. Data Binding Way: Java binding mainActivityBinding; @Override protected void onCreate(Bundle

    savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.main_activity); } private void updateUser(User user) { binding.setUser(user); } Call this to bind layout to Activity instead of calling setContentView() Bind user data to views
  4. Data Binding Way: XML <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="user" type="com.guendouz.androiddatabinding.model.User"/>

    </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv_firstname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{user.firstName}"/> <TextView android:id="@+id/tv_lastname" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{user.lastName}"/> </LinearLayout> </layout> Add <layout> to root Declare variable Bind firstname using expression language Bind lastname using expression language
  5. Basics: Expression language Mathematical + - / * % String

    concatenation + Logical && || Binary & | ^ Unary + - ! ~ Shift >> >>> << Comparison == > < >= <= instanceof, Cast Grouping () Literals character, String, numeric, null Method calls, field access Ternary operator ?: Array access [] Null coalescing operator ??
  6. Basics: Expression language android:text="@{user.firstName + user.lastName}" android:visibility="@{user.age < 13 ?

    View.GONE : View.VISIBLE}" android:text="@{user.displayName ?? user.firstName}" android:text="@{user.friends[0].firstName}"
  7. Basics: View Notification #1 public class User extends BaseObservable {

    private String firstName; @Bindable public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; notifyPropertyChanged(BR.firstName); } } Bindable getter Notify the view
  8. Basics: View Notification #2 public class User extends BaseObservable {

    public ObservableField<String> firstName; public void setFirstName(String firstName) { this.firstName = new ObservableField<>(firstName); } An Observable field
  9. Basics: Observable Objects • Observable objects extend BaseObservable class •

    Responsible for binding data to views • May contain business logic code public class User extends BaseObservable { private String firstName; @Bindable public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; notifyPropertyChanged(BR.firstName); } }
  10. Basics: Observable Fields public class User{ public final ObservableField<String> name

    = new ObservableField<String>(); public final ObservableInt age = new ObservableInt(); } user.name.set("Name"); user.age.set(20); An object wrapper to make it observable. Observable field classes may be used instead of creating an Observable object:
  11. Basics: Event Handling (Method References) public void contactAction(View view) {

    … } <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="@{user::contactAction}"/> Declare a method with a parameter Bind method to event using “::” The parameters of the method must match the parameters of the event listener.
  12. Basics: Event Handling (Listener Objects) public View.OnClickListener onClickContact; <Button android:layout_width="wrap_content"

    android:layout_height="wrap_content" android:onClick="@{user.onClickContact}"/> Declare the listener as a variable Bind it
  13. Basics: Event Handling (Lambda Expressions | Listener Bindings) public void

    contactAction(View view, User user) { … } <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="@{ (e) -> user.contactAction(e , user) }"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="@{ () -> user.contactAction(user) }"/> 1 2 Only your return value must match the expected return value of the listener
  14. Basics: Event Handling Which To Use ? Lambda expression Flexible

    Different parameters The expression is evaluated when the event occurs. Method references Fixed number of parameters The expression is evaluated at binding time Listener Objects Existing apps
  15. Binding Adapters @BindingAdapter({"imageUrl"}) public static void loadImage(ImageView view, String imageUrl)

    { Picasso.with(view.getContext()) .load(imageUrl) .placeholder(R.drawable.placeholder) .into(view); } app:imageUrl="@{viewModel.photoUrl}"
  16. To do • Two-way data binding • Binding Component •

    Binding Conversions • Binding methods • RecyclerView Binding
  17. Summary • Less boilerplate code • Generate code at compilation

    time (unlike ButterKnife and others) • Powered by Google
  18. Resources • Official Android guide https://developer.android.com/topic/libraries/data-binding/index.html • Android Data Binding

    https://realm.io/news/data-binding-android-boyar-mount/ • Archi: MVVM sample project https://github.com/ivacf/archi