android - 如何用 View 绑定(bind)替换 findViewById(v.getId()) ?

标签 android android-studio view binding

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

这是我的代码:

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

最佳答案

请提供 View Binding 的文档看看我相信你会发现它回答了你的问题。

但总而言之:

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

    android {
        ...
        buildFeatures {
            viewBinding true
        }
    }
    
  2. 对于具有类似于 result_profile.xml 的 xml 的 Fragment,将以以下格式生成绑定(bind)类: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
}
  • 对于 Activity :
  • 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 方法中的 View 与您的 View 绑定(bind) ID 进行比较,即

    v.id == binding.yourbutton.id
    

    switch 语句或 if 语句可用于检查哪个 id 与单击的 View 匹配。

    关于android - 如何用 View 绑定(bind)替换 findViewById(v.getId()) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65231824/

    相关文章:

    Android Studio Bumblebee Wifi 配对问题

    java - 访问旧应用程序时 list 合并失败

    android - 单击按钮时刷新 fragment View

    Android - 仅在父 View 上播放动画

    java - TCP/IP 打开连接

    android - 如何让 toast 在不扩展 Activity 的类里面工作?

    android - JavaBinder BINDER 事务失败

    android - 检测手机旋转(移动)

    ios - 如果我们点击背景中的任何地方,除了快速点击 popView 之外,如何删除 popView

    android - 从 android 程序运行 shell 命令