Data Binding

The Data Binding Library is a support library that allows us to bind UI components in our layouts to data sources in our app using a declarative format

Benefits :

  • Improves the performance of the app
  • Eliminates the use of findViewById() which makes the code concise, easier to read and maintain.
  • Recognizes errors during compile time

In build.gradle, under the android tab, add

buildFeatures {
dataBinding true
}
plugins {
    id 'kotlin-kapt'
}
annotationProcessor 'androidx.databinding:databinding-compiler:3.2.0-alpha16'

In an Activity :

class MainActivity : AppCompatActivity() {

private lateinit var binding : ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.btnRoll.setOnClickListener {
rollDice()
}
}

private fun rollDice() {
val data = when((1..6).random()) {
1 -> R.drawable.dice_1
2 -> R.drawable.dice_2
3 -> R.drawable.dice_3
4 -> R.drawable.dice_4
5 -> R.drawable.dice_5
else -> R.drawable.dice_6
}
binding.imgDice.setImageResource(data)
}
}

In a Fragment :

class HomeFragment : Fragment() {

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = DataBindingUtil.inflate<FragmentHomeBinding>(inflater,
R.layout.fragment_home, container, false)
return binding.root
}
}




in xml file, make the parent tag/layout as <layout> tag

if xml file is activity_main,xml then in the MainActivity class, we can access it as ActivityMainBinding class generated by data binding. We can omit setContentView(R.layout.activtiy_main) and use

 ActivityMainBinding activity = DataBindingUtil.setContentView(this, R.layout.actvitiy_main); or 

ActivityMainBinding activity = ActivityMainBinding.inflate(getLayoutInflater());

setContentView(activity.getRoot());

in xml, declare 

<data>

    <variable>

        name="my_variable"

        type="String"

    </variable>

    <variable>

        name="user"

        type="com.example.test.User"

    </variable>

</data>

<TextView>

    android:text="@{my_variable}"

    android:text="@{user.name}"

</TextView>

in MainActivity,

activity.setMyVariable("Hello");

User user = new User(Data);

activity.setUser(user);

in User class,

@BindingAdapter("android:loadImage")

in xml, 

android:loadImage="@{user.imageUrl}"

Comments

Popular posts from this blog

Android - Using KeyStore to encrypt and decrypt the data

Stack and Queue

Java Reflection API