Home > OS >  How to call a element from Layout without use findViewId() in Kotlin?
How to call a element from Layout without use findViewId() in Kotlin?

Time:05-14

I didn't know this was possible, but I was following an example and I see this piece of code:

import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

    toggleButtonGroup.addOnButtonCheckedListener { toggleButtonGroup, checkedId, isChecked ->
    //some code here 
    }
}

Here is the code: https://gist.github.com/smartherd/0803ba4e287d6aa0d441d0a221eeb013

"toggleButtonGroup" is the ID of the element in layout, and he doesn´t declare it anywhere in the MainActivity, how can I do this?

CodePudding user response:

What you saw is Kotlin synthetics and has been deprecated in favor of ViewBinding and is heavily discouraged to use. You should use ViewBinding instead.

Enable ViewBinding for your project by setting viewBinding build feature to true, inside your module-level build.gradle

android {
    ...
    buildFeatures {
        viewBinding = true
    }
    ...
}

By enabling this, Android studio will start generating viewBinding classes for your layouts.


Using ViewBinding inside an activity

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

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

        //here access your view using binding
        binding.toggleButtonGroup.addOnButtonCheckedListener { toggleButtonGroup, checkedId, isChecked ->
                //some code here 
        }    
    }
}

ActivityMainBinding is the class generated by Android Studio using the activity_main layout.


Using ViewBinding inside a fragment

class TestFragment: Fragment() {

    private var _binding: TestFragmentBinding? = null
    private val binding get() = _binding!!
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = TestFragmentBinding.inflate(inflater, container, false)
        val view = binding.root
        return view
    }
    
    override fun onDestroyView() {
        super.onDestroyView()

        //setting _binding to null is important to avoid any memory leaks
        _binding = null 
    }
}
  • Related