Home > Back-end >  Convert FindViewById to Binding
Convert FindViewById to Binding

Time:05-02

Hi guys how can I change this (FindviewById) to Data Binding because am having issues with calling the views to the list so I need to change the (fvbi) to (binding) or can I access my views here when im using the findviewbyid


import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
          setListeners()

    }// end of on create

    private fun setListeners() {
        val clickableViews: List<View> =
            listOf()

        for (item in clickableViews) {
            item.setOnClickListener { makeColored(it) }
        }
    }


    private fun makeColored(view: View) {
        when (view.id) {

            // Boxes using Color class colors for background
            R.id.box_one_text -> view.setBackgroundColor(Color.DKGRAY)
            R.id.box_two_text-> view.setBackgroundColor(Color.GRAY)

            // Boxes using Android color resources for background
            R.id.box_three_text -> view.setBackgroundResource(android.R.color.holo_green_light)
            R.id.box_four_text -> view.setBackgroundResource(android.R.color.holo_green_dark)
            R.id.box_five_text -> view.setBackgroundResource(android.R.color.holo_green_light)

            else -> view.setBackgroundColor(Color.LTGRAY)
        }
    }
}

CodePudding user response:

Yes you can access your views with findViewById

val clickableViews: List<View> =
        listOf(findViewById(R.id.box_one_text), ...)

or with view binding you can do like this,

val clickableViews: List<View> =
        listOf(binding.boxOneText, ...)

CodePudding user response:

Using the binding structure makes more sense now and saves you a lot of code. eg:if the activity was called HomeActivity it would be ActivityHomeBinding

build.gradle(module)

buildFeatures {
        viewBinding true
        dataBinding true
    }

MainActivity

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHomeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.apply {
         //eg:
         button.setOnClickListener{
           }
        }
    }
  • Related