gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:26:36 25 4
gpt4 key购买 nike

通过点击一个按钮,我可以通过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 的文档看看我相信你会发现它回答了你的问题。
但总而言之:

  • 在模块级 build.gradle 添加:
    android {
    ...
    buildFeatures {
    viewBinding true
    }
    }
  • 对于 fragment 使用像 result_profile.xml 这样的 xml将按以下格式生成绑定(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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com