【问题标题】:How to replace findViewById(v.getId()) with View Binding?如何用视图绑定替换 findViewById(v.getId())?
【发布时间】:2021-03-21 17:11:50
【问题描述】:

通过点击一个按钮,我可以通过findViewById(v.getId())找到该按钮的id。如何用 View Binding 替换它?

这是我的代码:

fun TastoClick(v: View) {
    val btn = findViewById(v.getId()) as Button
    var name = btn.text.toString().toInt()
}

【问题讨论】:

    标签: android android-studio view binding


    【解决方案1】:

    请务必查看View Binding 的文档,我相信您会发现它回答了您的问题。

    但总而言之:

    1. 在模块级build.gradle添加:

      android {
          ...
          buildFeatures {
              viewBinding true
          }
      }
      
    2. 对于带有像result_profile.xml 这样的xml 的Fragment,将生成格式为:ResultProfileBinding 的绑定类,然后您需要为该类设置一个实例,如下所示:

    result_profile.xml:

    <LinearLayout ... >
        <TextView android:id="@+id/name" />
        <ImageView android:cropToPadding="true" />
        <Button android:id="@+id/button"
            android:background="@drawable/rounded_button" />
    </LinearLayout>
    

    ResultProfileFragment.kt:

    private var _binding: ResultProfileBinding? = null
    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = ResultProfileBinding.inflate(inflater, container, false)
        val view = binding.root
        return view
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
    
    1. 对于活动

    ResultProfileActivity.kt:

    private lateinit var binding: ResultProfileBinding
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ResultProfileBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
    }
    

    然后您可以像这样访问布局元素:

    binding.name.text = viewModel.name
    binding.button.setOnClickListener { viewModel.userClicked() }
    

    更新:

    如果您有多个按钮的一个侦听器,您可以简单地将传递给 onClick 方法的视图与您的视图绑定 ID 进行比较,即

    v.id == binding.yourbutton.id
    

    可以使用 switch 语句或 if 语句来检查哪个 id 与被点击的视图匹配。

    【讨论】:

    • 谢谢,但这不允许我获取点击按钮的 ID
    • 我已经在使用 View Binding 并且想替换我代码中的所有 findViewbyId()
    • 只需调用 binding.view.id,你就会得到你的 id。
    • 正如@benyuss 所说,如果您需要id,您可以使用他显示的代码,您可以删除 findViewById 并改用binding.YOUR_ELEMENT_ID,正如我在回答中所展示的那样。您不需要按 id 获取视图,因为您可以使用您给它的 id 简单地引用它希望这是有道理的,如果它通过使用此答案旁边的复选标记解决了您的问题,请将此标记为已解决跨度>
    • 在我的 xml 文件中,我有“Tasto1”、“Tasto2”、“Tasto3”等,具有相同的“onClick”。不知道点击的是哪一个。使用 findViewById(v.getId()) 我明白了。当我知道按钮的 id 时,我可以使用 binding.view.id...
    【解决方案2】:

    科特林

    val btn = binding.root.findViewById<Button>(v.id)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      相关资源
      最近更新 更多