Search code examples
kotlindata-bindingviewmodel

How can i use DataBinding for TextView?


i have a problem, i dont know how to use DataBinding for TextView. i made a DataBinding for Glide and it success, but for TextView i dont know how to do it

this is the code

viewModel2.shouldShowImageProfile.observe(this) {
        Glide.with(binding.root)
            .load(it)
            .circleCrop()
            .into(binding.rivProfile)
    }

    viewModel2.shouldShowUsername.observe(this){
        TextView.with(binding.root) <- the TextView
            .load(it)
            .into(binding.tvHello)
    }

Solution

  • I wrote my answer making an assumption about shouldShowUsername, but as that's your String value, you can do something like this:

    viewModel2.shouldShowUsername.observe(this) { shouldShowUsername ->
        binding.tvHello.isVisible = !shouldShowUsername.isNullOrEmpty()
        binding.tvHello.text = shouldShowUsername
    }
    

    That'll cause your TextView to only be displayed when shouldShowUsername has a proper value then take that value and assign it to the TextView. If you want the TextView to always show up, you can skip that first line within the block.