In this chapter of the BMI Calculator application we are going to add to the layouts custom attributes using Data Binding Adapter.
With Data Binding Adapter we will create for the result_fragment.xml custom attributes to show in text form a short evaluation of the result BMI value. Then for this text, we gonna define some conditions to change its color. The result will look like below.
The starter project for this lecture is available on GitHub. Just download it using the below link.
After the download, extract the app from the .ZIP file and import it in Android Studio (File -> New -> Import Project…)
Step 2 - Create 2 enums
We are going to create one more file, what will have 2 enum classes.
So, also in the utils folder, create a new Koltin file and name it as “Enums”.
The first class will contain the ranges of the BMIs. Based on these values we will tell the user that the BMI value is healthy or not.
So, copy and paste the below enum class into the Enums.kt file.
The next enum will be the textual evaluation of the BMI calculation.
Paste it after the first enum class.
Step 3 - Create the Data Binding Adapters
Our first adapter will set the text of the TextView based on what the end BMI result is.
Paste the below method into the DataBindingAdapter.kt file.
Note the next points
- To create a Data Binding Adapter, you have to annotate the function with @BindingAdapter. Thenafter in the parentheses you can specify the name of the attribute, what we can use in the layout files.
- In the header of the function check out the attributes. The first attribute has to be always the type of the view what you want to use it for.
- Finally using a when expression we will set the text of the TextView.
The second adapter will set the color of the same TextView using the same Float value.
So, copy and pate the below method after the first one into the DataBindingAdapter.kt file.
Step 4 - Usage of the Data Binding Adapters
The last step of this chapter is to add the above created new custom attributes to the text evaluation in the result_fragment.xml file. So, open it from teh res->layout folders and add the below lines to the tv_evaluation TextView.
Note that we can pass the context to the Data Binding Adapter using the context variable, which is in our case the ResultFragment’s context.
Note also that we are passing here the LiveData from the ResultViewModel. This LiveData contains the calculated BMI value.
Finally the source code of the tv_evaluation TextView looks like below.
Run the app
It’s time, run the app. 😊
If you have done perfectly this chapter, then on the result screen in the result card you should have the colored textual evaluation above of the BMI’s value.
Well done. 😎
I hope the description was understandable and clear. But, if you have still questions, then leave me comments below! 😉
Have a nice a day! 🙂
[Total: 0 Average: 0]