如何在不使用 Kotlin 中的 findViewId() 的情况下从 Layout 调用元素?

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

我不知道这是可能的,但我正在关注一个例子,我看到了这段代码:

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 
    }
}

代码如下: https://gist.github.com/smartherd/0803ba4e287d6aa0d441d0a221eeb013

"toggleButtonGroup"是layout中元素的ID,他没有在MainActivity的任何地方声明,请问如何实现?

您看到的是 Kotlin syntheticsdeprecated 支持 ViewBinding,强烈建议不要使用。您应该改用 ViewBinding

通过将 viewBinding 构建功能设置为 true,在您的 module-level build.gradle

中为您的项目启用 ViewBinding
android {
    ...
    buildFeatures {
        viewBinding = true
    }
    ...
}

通过启用此功能,Android studio 将开始为您的 layouts.

生成 viewBinding

activity

中使用 ViewBinding
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 是由 Android Studio 使用 activity_main 布局生成的 class


fragment

中使用 ViewBinding
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 
    }
}