作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
通过点击一个按钮,我可以通过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 的文档看看我相信你会发现它回答了你的问题。
但总而言之:
android {
...
buildFeatures {
viewBinding true
}
}
result_profile.xml
这样的 xml将按以下格式生成绑定(bind)类:ResultProfileBinding
然后,您需要为该类设置一个实例,如下所示:<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
}
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/
我是一名优秀的程序员,十分优秀!