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

Android Jetpack's Data Binding Library

Android Jetpack's Data Binding Library

Android Jetpack's Data Binding Library has been there since some time but not many people have got chance to actually use it. This presentation will help you to understand how this Library can be used to avoid writing "findViewById" and directly access the views with their id names in java/kotlin class.

It explains how you can do most of the calculations(Mathematical, Logical, Binary, Ternary) in the XML itself.

Also, you can override existing attributes of a View, example "android:text" to behave in your own way or you can create your own attributes and set it in the views in XML. This is super effective.

We were not aware that the approach when we do android:onClick = "methodName" and defining the method in your java/kotlin class later, uses REFLECTION internally, which is pretty slow. Data Binding provides solution to it by its "Method References" and "Listener Bindings" that happens all at compile time and the most interesting part "Observables".

Avatar for Aayushma Agrawal

Aayushma Agrawal

September 22, 2019
Tweet

More Decks by Aayushma Agrawal

Other Decks in Programming

Transcript

  1. Let’s bond with Android Jetpack’s Data Binding Aayushma Agrawal Android

    Developer At Lenskart Twitter:- @AgrawalAayushma
  2. WHAT WE WILL BE DOING TODAY? • Learning Data Binding

    through a LIVE example. • Learning KEY terminologies to get started with it.
  3. TOPICS TO BE DISCUSSED • Introduction to Android Jetpack’s Data

    Binding Library • Enabling Data Binding Library in project. • Digging Deep to learn: ◦ <data>, <variable> and @{} ◦ Event Binding ◦ Expression ◦ Binding Adapters ◦ Observables • Your Homework :p
  4. INTRODUCTION • Data Binding Library was founded in 2015. •

    Official Source says: ◦ The Data Binding Library is a support library that allows you to bind UI components in your layout to data sources in your app using a declarative format rather than programmatically. • Data Binding Library executes during compile time and saves you from any unexpected errors at Runtime.
  5. STEP 1: ENABLING DATA BINDING LIBRARY • Create a new

    project or open an existing project. • Go to build.gradle(Module) file in your project.
  6. Step 2 : <layout> tag • Old Code: <LinearLayout xmlns:android

    = “https://schemas.android.com/apk/res/android” android:layout_width = “match_parent” android:layout_height = “match_parent” <TextView> ….. <ImageView> </LinearLayout>
  7. New Code.. • Start your XML file with <layout> tag.

    <layout> <LinearLayout xmlns:android = “https://schemas.android.com/apk/res/android” android:layout_width = “match_parent” <TextView> ….. <ImageView> </LinearLayout> </layout>
  8. At the background? - Binding classes are Auto-Generated Name of

    the xml : activity_main Default Binding class Generated : ActivityMainBinding When we create reference of this class in Activity/Fragment, you can access all the variables or views present in its corresponding XML directly by their ids.
  9. Changes required in the Activity Then…. setContentView(R.layout.activity_main); Now.. ActivityMainBinding activityMainBinding

    ; activityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);
  10. Auto Generated Binding Class public abstract class ActivityMainBinding extends ViewDataBinding

    { @NonNull public final Button addToCartButton; @NonNull public final ImageView giftImageview; @NonNull public final Button buyNowButton; . . . } android:id="@+id/gift_imageview" android:id="@+id/add_to_cart_button" android:id="@+id/buy_now_button"
  11. Let’s Look at the Basics public class MainActivity extends AppCompatActivity

    { EditText firstNameEditText, lastNameEditText, emailEditText, organizationEditText, designationEditText, addressEditText; Button submitButton; }
  12. Initializing Views.. lastNameEditText = findViewById(R.id.last_name_edittext); orgEditText = findViewById(R.id.organization_edittext); designationEditText =

    findViewById(R.id.designation_edittext); addressEditText = findViewById(R.id.address_edittext); mobileNumberEditText = findViewById(R.id.mobile_no_edittext); emailEditText = findViewById(R.id.email_edittext); submitButton = findViewById(R.id.submit_button); }
  13. Initializing Views.. lastNameEditText = findViewById(R.id.last_name_edittext); orgEditText = findViewById(R.id.organization_edittext); designationEditText =

    findViewById(R.id.designation_edittext); addressEditText = findViewById(R.id.address_edittext); mobileNumberEditText = findViewById(R.id.mobile_no_edittext); emailEditText = findViewById(R.id.email_edittext); submitButton = findViewById(R.id.submit_button); }
  14. Initializing Views.. lastNameEditText = findViewById(R.id.last_name_edittext); orgEditText = findViewById(R.id.organization_edittext); designationEditText =

    findViewById(R.id.designation_edittext); addressEditText = findViewById(R.id.address_edittext); mobileNumberEditText = findViewById(R.id.mobile_no_edittext); emailEditText = findViewById(R.id.email_edittext); submitButton = findViewById(R.id.submit_button); }
  15. Initializing Views.. lastNameEditText = findViewById(R.id.last_name_edittext); orgEditText = findViewById(R.id.organization_edittext); designationEditText =

    findViewById(R.id.designation_edittext); addressEditText = findViewById(R.id.address_edittext); mobileNumberEditText = findViewById(R.id.mobile_no_edittext); emailEditText = findViewById(R.id.email_edittext); submitButton = findViewById(R.id.submit_button); }
  16. Initializing Views.. lastNameEditText = findViewById(R.id.last_name_edittext); orgEditText = findViewById(R.id.organization_edittext); designationEditText =

    findViewById(R.id.designation_edittext); addressEditText = findViewById(R.id.address_edittext); mobileNumberEditText = findViewById(R.id.mobile_no_edittext); emailEditText = findViewById(R.id.email_edittext); submitButton = findViewById(R.id.submit_button); }
  17. Initializing Views.. lastNameEditText = findViewById(R.id.last_name_edittext); orgEditText = findViewById(R.id.organization_edittext); designationEditText =

    findViewById(R.id.designation_edittext); addressEditText = findViewById(R.id.address_edittext); mobileNumberEditText = findViewById(R.id.mobile_no_edittext); emailEditText = findViewById(R.id.email_edittext); submitButton = findViewById(R.id.submit_button); }
  18. Initializing Views.. lastNameEditText = findViewById(R.id.last_name_edittext); orgEditText = findViewById(R.id.organization_edittext); designationEditText =

    findViewById(R.id.designation_edittext); addressEditText = findViewById(R.id.address_edittext); mobileNumberEditText = findViewById(R.id.mobile_no_edittext); emailEditText = findViewById(R.id.email_edittext); submitButton = findViewById(R.id.submit_button); }
  19. SURPRISE…….NO MORE “findViewById” public class MainActivity extends AppCompatActivity { //Auto-

    Generated binding class ActivityMainBinding activityMainBinding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main); //Access all your views using the above binding variable } }
  20. ACCESSING VIEWS DIRECTLY @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

    activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); //Access all your views using the above binding variable activityMainBinding.welcomeTitle.setText("Welcome to DevFest 19"); String firstName = activityMainBinding.firstNameEdittext.getText().toString(); } android:id=“@+id/first_name_edittext”
  21. <data> and @{} • An Activity comprises of IMPORTS, VARIABLES

    , METHODS. • Similarly, XML declares “import” and “variables” through <data> tag. • Whenever you want to access /assign value to views, use @{ }
  22. EXAMPLE <layout> <data> <import type="android.view.View"/> <!--String variable --> <variable name="variableName"

    type="String"/> </data> <layout> Has an internal getter getFirstName() and setter setFirstName ()with it by which it can be accessed.
  23. More about <data> and <variable> tags • Each variable declared

    inside <variable> tag has an internal setter and getter to it. • If we want to pass value to those variables through Activity, we can do that by calling setter method of the variable .
  24. EXAMPLE :- SETTING TEXT TO TEXTVIEW • There are two

    ways:- 1. Doing it from the Activity activityMainBinding.welcomeTitle.setText("Welcome to DevFest 19"); 2. Doing it from the XML android:text=@{variableName}
  25. EXAMPLE :- SET TEXT TO TEXTVIEW • There are TWO

    ways: 1. Directly accessing the view by its “id” android:id="@+id/welcome_title" In Activity, just write, activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) activityMainBinding.welcomeTitle.setText("Welcome to DevFest 19");
  26. EXAMPLE :- SET TEXT TO TEXTVIEW 2. Using user defined

    VARIABLE declared in XML • Create a variable, say headerText, inside <variable> tag. • Assign this variable to the TextView • Pass value to this variable through its from Activity.
  27. EXAMPLE :- SET TEXT TO TEXTVIEW • Create a variable,

    say headerText, inside <variable> tag. <variable name="headerText" type="String"/>
  28. EXAMPLE :- SET TEXT TO TEXTVIEW • Assign this variable

    to the TextView <TextView android:id="@+id/welcome_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{headerText}" />
  29. EXAMPLE :- SET TEXT TO TEXTVIEW • Pass the value

    to headerText variable through its SETTER method from Activity. activityMainBinding.setHeaderText("Welcome to DevFest 19"); AUTO GENERATED SETTER FOR THE XML variable.
  30. SO FAR IN DEEP DIGGING DATA BINDING ◦ <data>, <variable>

    and @{} ◦ Event Binding ◦ Expression ◦ Binding Adapters ◦ Observables
  31. BUTTON CLICK - WITHOUT DATA BINDING @Override protected void onCreate(Bundle

    savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); submitButton = findViewById(R.id.submit_button); submitButton.setOnClickListener(this); //Implement the Listener interface in activity }
  32. BUTTON CLICK - WITHOUT DATA BINDING public void onClick(View view)

    { if(view.getId() == R.id.submit_button) { //Do the stuff } } Note the signature of onClick(). It takes “View” as the first parameter.
  33. GOAL - CODE SMARTLY!! Another way of handling button click

    is android:onClick = “methodName” (Uses Reflection internally) Also, the method declared here , should be defined in the corresponding activity itself. So , standard onClick() is slow, compared to the data binding mechanisms that DOES NOT use REFLECTION.
  34. METHOD REFERENCES • Any STATIC OR INSTANCE method in any

    class that has same signature like the default onClick(), can be directly called from the XML public void showOrderDetails(View view) { }
  35. METHOD REFERENCES Example , you have a method say “showOrderDetails()”

    in the OrderDetails class. class OrderDetails { public void showOrderDetails(View v) { //Write your logic here } }
  36. METHOD REFERENCES Existing Way:- If you want to call the

    same method from Activity, how will you do that? OrderDetails orderDetailsObj = new OrderDetails(); orderDetailsObj.showOrderObj(view); objectName.methodName(parameter)
  37. METHOD REFERENCES • In XML, first declare a variable of

    OrderDetails class, since you want to call its method: <variable name="orderDetails" type="com.example.OrderDetails"/>
  38. METHOD REFERENCES 2. Pass the value to this object reference/variable

    from your Activity binding.setOrderDetails(orderDetailsObj);
  39. METHOD REFERENCES • In XML, call this method from Button

    like shown below <Button android:id="@+id/add_to_cart_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="@{orderDetails.showOrderDetails}" android:text="@string/add_to_cart" /> @{orderDetails :: showOrderDetails} OR
  40. LISTENER BINDINGS • Any method that DOES NOT match with

    the default signature of onClick(), we can still call it from XML using LISTENER BINDINGS . • Example , you have a method say “showOrderDetails(int orderId)” in the OrderDetails class.
  41. LISTENER BINDINGS 1. Step 1, create an integer orderId that

    you need to pass to the method. <variable name="orderId" type="int"/> <variable name="orderDetails" type="com.example.OrderDetails"/>
  42. LISTENER BINDINGS 2. Pass the values to these variables from

    your Activity binding.setOrderId(5); binding.setOrderDetails(orderDetailsObj);
  43. LISTENER BINDINGS 3. Write code in Button as shown below:-

    <Button android:id="@+id/add_to_cart_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="@{() -> orderDetails.showOrderDetails(orderId)}" android:text="@string/add_to_cart" />
  44. LISTENER BINDINGS Example the signature of method is:- class OrderDetails

    { public void showOrderDetails(View view, int orderId) { //Write your logic here } } If your method wants parameter view also, Then???
  45. LISTENER BINDINGS • You can just write your Button code

    as:- <Button android:id="@+id/add_to_cart_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="@{(v) -> orderDetails.showOrderDetails(v, orderId)}" android:text="@string/add_to_cart" />
  46. Expressions • Mathematical + - / * % • String

    concatenation + • Logical && || • Binary & | ^ • Unary + - ! ~ • Shift >> >>> << • Comparison == > < >= <= • instanceOf
  47. Expressions • Grouping () • Literals — character, String, numeric,

    null • Cast • Method calls • Field access • Array access [] • Ternary operator? :
  48. EXPRESSIONS IN XML You can even do concatenation in XML

    Like <TextView android:id="@+id/price_textview" android:layout_width="wrap_content" android:layout_height="wrap_conten android:text=‘@{“Price” + price}’ />
  49. SO FAR IN DEEP DIGGING DATA BINDING ◦ <data>, <variable>

    and @{} ◦ Event Binding ◦ Expression ◦ Binding Adapters ◦ Observables
  50. BINDING ADAPTERS • Binding Adapters are CUSTOM SETTERS • Helps

    you to add extra functionality to your view. • You can override existing behaviour of an attribute. • Gives you the flexibility to create your own attributes in XML
  51. BINDING ADAPTERS - USE CASE • Overriding existing behaviour of

    an attribute. I want , whatever value I enter in the textView should append “Welcome” to it. Why write redundant code in Activity for each textview like:- textView.setText(“Welcome”+ text);
  52. BINDING ADAPTERS - USE CASE Note:- 1. Contains the name

    of the attribute you want to override. Impact :- All the textviews in the entire app, will have “Welcome” appended in their text. STRICTLY NOT RECOMMENDED to do this. 2. The first parameter of the method has to be the VIEW TYPE(here textview) 3. Binding Adapter method is static.
  53. BINDING ADAPTERS • Creating your own custom attributes for xml

    Problem :- All the textviews in the entire app, will have “Welcome” appended in their text. STRICTLY NOT RECOMMENDED to do this. Solution :- Create your own attributes using Binding Adapter and get the flexibility to assign it ONLY to views which you want to customize .
  54. BINDING ADAPTER - USE CASE public class BindingAdapters { @BindingAdapter("strikeText")

    public static void setStrikeText(TextView view, String textToStrike) { ... } } Name of the method does not matter.
  55. BINDING ADAPTER - USE CASE public class BindingAdapters { @BindingAdapter("strikeText")

    public static void setStrikeText(TextView view, String textToStrike) { view.setText(textToStrike, TextView.BufferType.SPANNABLE); Spannable spannable = (Spannable) view.getText(); spannable.setSpan(new StrikethroughSpan(), 0, view.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } }
  56. BINDING ADAPTER - EXAMPLE 2 • Loading image into Imageview

    using Data Binding android:src="@drawable/champagne" The above statement returns you a drawable (image) , whereas if we directly try to use any Image Library like Picasso/ Glide , they DO NOT return anything to the android:src, hence does not work.
  57. BINDING ADAPTER - EXAMPLE 2 • Loading image into Imageview

    using Data Binding <ImageView android:id="@+id/gift_imageview" android:layout_width="match_parent" android:layout_height="300dp" android:src = “Picasso.with(imageView.getContext()).load(url).into(gift_imageview);" />
  58. BINDING ADAPTER - EXAMPLE 2 • Right way of doing

    it with Data Binding @BindingAdapter("imageUrl") public static void setImageUrl(ImageView imageView, String imageUrl) { if (!Helpers.isNullOrEmpty(imageUrl)) Picasso.with(imageView.getContext()).load(imageUrl).into(imageView); }
  59. BINDING ADAPTER - EXAMPLE 2 • Assign the CUSTOM SETTER

    defined in BindingAdapter class to Imageview <ImageView android:id="@+id/bouquet_imageview" android:layout_width="match_parent" android:layout_height="300dp" app:imageUrl="@{url}" /> What’s this?
  60. BINDING ADAPTER - EXAMPLE 2 • What is “url” in

    the app:imageUrl="@{url}" <variable name="url" type="String"/>
  61. BINDING ADAPTER - EXAMPLE 2 • You can pass value

    to this variable through your ACTIVITY binding.setUrl("https://postimg.cc/68yJtvjw");
  62. SO FAR IN DEEP DIGGING DATA BINDING ◦ <data>, <variable>

    and @{} ◦ Event Binding ◦ Expression ◦ Binding Adapters ◦ Observables
  63. BASE OBSERVABLE AND @BINDABLE public class BankAccount extends BaseObservable {

    private double bankBalance; @Bindable public double getBankBalance() { return bankBalance; } public void setBankBalance(Double bankBalance) { //code to set the values } Use it with all the getter methods of variables, whose value you want to observe.
  64. BASE OBSERVABLE AND @BINDABLE public class BankAccount extends BaseObservable {

    private double bankBalance; @Bindable public double getBankBalance() { return bankBalance; } public void setBankBalance(Double bankBalance) { this.bankBalance = bankBalance; notifyPropertyChanged(BR.bankBalance); } } Generates the entry of “bankBalance” variable in BR file.
  65. BR FILE • It’s same like the R class file

    which is auto-generated for all ids inside your layout, or references. • The Bindable annotation generates an entry in the BR class file during compilation. • So it will contain references to all property annotated with @Bindable.
  66. OBSERVABLE FIELDS AND TYPES • In the above approach, we

    had to separately create a class and extend it with Base Observable. • Use @Bindable and call notifyPropertyChanged() to notify. • Well, to further simplify this mechanism we have Observable Fields.
  67. OBSERVABLE FIELDS AND TYPES • ObservableBoolean • ObservableByte • ObservableChar

    • ObservableShort • ObservableInt • ObservableLong • ObservableFloat • ObservableDouble • ObservableParcelable
  68. OBSERVABLE FIELDS AND TYPES • Observable fields are self-contained observable

    objects that have a single field. • To use this mechanism, create a public final property in the Java programming language.
  69. OBSERVABLE FIELDS AND TYPES EXAMPLE Step 1. Create the observable

    fields in a class , say Address. public class Address { public final ObservableField<String> firstName = new ObservableField<>(); public final ObservableField<String> lastName = new ObservableField<>(); public final ObservableField<String> address = new ObservableField<>(); public final ObservableField<String> mobileNumber = new ObservableField<>(); }
  70. OBSERVABLE FIELDS AND TYPES EXAMPLE Step 1. Create the observable

    fields in a class , say Address. public class Address { public final ObservableField<String> firstName = new ObservableField<>(); public final ObservableField<String> lastName = new ObservableField<>(); public final ObservableField<String> address = new ObservableField<>(); public final ObservableField<String> mobileNumber = new ObservableField<>(); }
  71. OBSERVABLE FIELDS AND TYPES EXAMPLE Step 1. Create the observable

    fields in a class , say Address. public class Address { public final ObservableField<String> firstName = new ObservableField<>(); public final ObservableField<String> lastName = new ObservableField<>(); public final ObservableField<String> address = new ObservableField<>(); public final ObservableField<String> mobileNumber = new ObservableField<>(); }
  72. OBSERVABLE FIELDS AND TYPES EXAMPLE Step 1. Create the observable

    fields in a class , say Address. public class Address { public final ObservableField<String> firstName = new ObservableField<>(); public final ObservableField<String> lastName = new ObservableField<>(); public final ObservableField<String> address = new ObservableField<>(); public final ObservableField<String> mobileNumber = new ObservableField<>(); }
  73. OBSERVABLE FIELDS AND TYPES EXAMPLE One-way Data Binding - Data

    flows in uni direction, only from model to the UI. android:text= “@{variableName}” Two-way Data Binding - Data flows in both directions, Changes in the UI gets reflected in the model. android:text= “@={variableName}”
  74. OBSERVABLE FIELDS AND TYPES EXAMPLE 2. Populate the Strings with

    values entered in Edittext as shown:- <EditText android:id="@+id/first_name_edittext" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@={address.firstName}" android:hint="@string/first_name" /> Notice the “ @={ } “ You use it, when you want to get the value from view
  75. OBSERVABLE FIELDS AND TYPES EXAMPLE Step 2:- Declare the necessary

    variables • You want to access the above variables of “Address” class from layout. • Create reference of Address class in XML . <variable name="address" type="com.example.bouquetapplication.Address"/>
  76. OBSERVABLE FIELDS AND TYPES EXAMPLE Step 3:- Set values to

    the variables defined public class AddressActivity extends AppCompatActivity { ActivityAddressBinding addressBinding; //AUTO-GENERATED BINDING CLASS @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addressBinding = DataBindingUtil.setContentView(this, R.layout.activity_address); addressBinding.setAddress(new Address()); } }
  77. OBSERVABLE FIELDS AND TYPES EXAMPLE 2. Populate the Strings with

    values entered in Edittext as shown:- <EditText android:id="@+id/last_name_edittext" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@={address.lastName}" android:hint="@string/last_name" />
  78. OBSERVABLE FIELDS AND TYPES EXAMPLE 2. Populate the Strings with

    values entered in Edittext as shown:- <EditText android:id="@+id/address_edittext" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@={address.userAddress}" android:hint="@string/address" />
  79. OBSERVABLE FIELDS AND TYPES EXAMPLE 2. Populate the Strings with

    values entered in Edittext as shown:- <EditText android:id="@+id/amobileNumber_edittext" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@={address.mobileNumber}" android:hint="@string/address" />
  80. OBSERVABLE FIELDS AND TYPES EXAMPLE We want to enable the

    submit button, only when firstName, lastName , mobileNumber and address is filled. Step 3:- Write the necessary logic in the class for above requirement
  81. OBSERVABLE FIELDS AND TYPES EXAMPLE Step 4:- Set the integer

    to Button <Button android:id="@+id/submit_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="@{address.submitButtonVisibility}" android:onClick="@{() -> address.submitButtonClicked(context)}" android:text="Submit" />
  82. public final ObservableField<Integer> submitButtonVisibility = new ObservableField<Integer>(firstName, lastName, address, mobileNumber)

    { @Override public Integer get() { if(firstName.get() != null && lastName.get()!=null && address.get()!=null && mobileNumber.get()!=null) { boolean areAllFieldsFilled = !firstName.get().isEmpty() && !lastName.get().isEmpty() && !address.get().isEmpty() && !mobileNumber.get().isEmpty(); if (areAllFieldsFilled) return View.VISIBLE; else return View.INVISIBLE; } return View.INVISIBLE; } OBSERVABLE FIELDS AND TYPES EXAMPLE
  83. public final ObservableField<Integer> submitButtonVisibility = new ObservableField<Integer>(firstName, lastName, address, mobileNumber)

    { @Override public Integer get() { if(firstName.get() != null && lastName.get()!=null && address.get()!=null && mobileNumber.get()!=null) { boolean areAllFieldsFilled = !firstName.get().isEmpty() && !lastName.get().isEmpty() && !address.get().isEmpty() && !mobileNumber.get().isEmpty(); if (areAllFieldsFilled) return View.VISIBLE; else return View.INVISIBLE; } return View.INVISIBLE; } } OBSERVABLE FIELDS AND TYPES EXAMPLE
  84. public final ObservableField<Integer> submitButtonVisibility = new ObservableField<Integer>(firstName, lastName, address, mobileNumber)

    { @Override public Integer get() { if(firstName.get() != null && lastName.get()!=null && address.get()!=null && mobileNumber.get()!=null) { boolean areAllFieldsFilled = !firstName.get().isEmpty() && !lastName.get().isEmpty() && !address.get().isEmpty() && !mobileNumber.get().isEmpty(); if (areAllFieldsFilled) return View.VISIBLE; else return View.INVISIBLE; } return View.INVISIBLE; } } OBSERVABLE FIELDS AND TYPES EXAMPLE
  85. public final ObservableField<Integer> submitButtonVisibility = new ObservableField<Integer>(firstName, lastName, address, mobileNumber)

    { @Override public Integer get() { if(firstName.get() != null && lastName.get()!=null && address.get()!=null && mobileNumber.get()!=null) { boolean areAllFieldsFilled = !firstName.get().isEmpty() && !lastName.get().isEmpty() && !address.get().isEmpty() && !mobileNumber.get().isEmpty(); if (areAllFieldsFilled) return View.VISIBLE; else return View.INVISIBLE; } return View.INVISIBLE; } } OBSERVABLE FIELDS AND TYPES EXAMPLE
  86. public final ObservableField<Integer> submitButtonVisibility = new ObservableField<Integer>(firstName, lastName, address, mobileNumber)

    { @Override public Integer get() { if(firstName.get() != null && lastName.get()!=null && address.get()!=null && mobileNumber.get()!=null) { boolean areAllFieldsFilled = !firstName.get().isEmpty() && !lastName.get().isEmpty() && !address.get().isEmpty() && !mobileNumber.get().isEmpty(); if (areAllFieldsFilled) return View.VISIBLE; else return View.INVISIBLE; } return View.INVISIBLE; } } OBSERVABLE FIELDS AND TYPES EXAMPLE
  87. public final ObservableField<Integer> submitButtonVisibility = new ObservableField<Integer>(firstName, lastName, address, mobileNumber)

    { @Override public Integer get() { if(firstName.get() != null && lastName.get()!=null && address.get()!=null && mobileNumber.get()!=null) { boolean areAllFieldsFilled = !firstName.get().isEmpty() && !lastName.get().isEmpty() && !address.get().isEmpty() && !mobileNumber.get().isEmpty(); if (areAllFieldsFilled) return View.VISIBLE; else return View.INVISIBLE; } return View.INVISIBLE; } } OBSERVABLE FIELDS AND TYPES EXAMPLE
  88. OBSERVABLE FIELDS EXAMPLE Step 5:- Showing Toast in Button click

    <Button android:id="@+id/submit_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="@{address.submitButtonVisibility}" android:onClick="@{() -> address.submitButtonClicked(context)}" android:text="Submit" />
  89. OBSERVABLE FIELDS AND TYPES EXAMPLE /*Note calling this method from

    XML, and even View is not needed as first parameter here*/ public void submitButtonClicked(Context context) { Toast.makeText(context,"Your Order is successfully Placed", Toast.LENGTH_LONG).show(); }
  90. OBSERVABLE FIELDS AND TYPES EXAMPLE • Passing the context from

    Activity to XML <variable name="context" type="com.example.bouquetapplication.AddressActivity"/> • Setting the context in Activity addressBinding.setContext(this);
  91. RECAP.. • No findViewById required. • You can reference views

    directly from java class by the “id” • Initialize your imports and variables in the XML inside <data> tag. • Event clicks can be handled in the XML by calling the appropriate methods ,having SAME(METHOD REFERENCES) or DIFFERENT(LISTENER BINDINGS) signatures from onClick() . • You can do mathematical, logical, ternary operations etc in XML itself. • Boilerplate code is largely reduced by using Observables.
  92. HOMEWORK TIME!! Imagine you are in a PET shop and

    you have finalized that you are buying Golden Retriever Dog. Design a screen that shows the details of the Dog. Its name, breed, age and other useful information. Also you have to fill your contact details(Full Name , Mobile Number) before you can actually adopt that cute creature.
  93. COMMON ERRORS WHILE YOU START • You missed to enable

    data binding in gradle. • Putting xmlns: tools in <layout> giving you compiler issues. • You used “@{“Hi” + “123” }” for concatenation instead of ‘@{“Hi” + “123”}’ , so the outside QUOTES matter!! • Image not loading through Binding Adapters. Wait did you give Internet permissions in the Manifest? • What is even the issue?????????
  94. Say Bye to Boilerplate Code and Hii to Data Binding

    Lib. Twitter : @AgrawalAayushma