英文:
onClick function for multiple buttons
问题
如何为多个按钮设置点击事件(或点击监听器)?原因是我不想为每个按钮编写相同的代码,唯一不同的变量只是每个按钮的“Feeling”。
这是我的代码:(如果不太明白,不好意思,我只是在做一些实验!)
fun onClick(view: View) {
val database = FirebaseDatabase.getInstance()
val myRef = database.getReference("Users")
val userLocation = "New York"
val userId = myRef.push().key
val info = Users(Feeling = "Good", Location = userLocation)
if (userId != null) {
myRef.child(userId).setValue(info)
}
}
来自类文件的部分:
class Users(val Feeling: String, val Location: String) {
constructor() : this("","") {
}
}
<details>
<summary>英文:</summary>
How would I set an onclick function (or onclicklistner) to multiple buttons? The reason being, is I don't want to have to write this same code for each button, where the only different variable would be "Feeling" for each button.
This is my code: *(Sorry if it doesn't make sense, I'm just experimenting right now!)*
fun onClick(view: View) {
val database = FirebaseDatabase.getInstance()
val myRef = database.getReference("Users")
val userLocation = "New York"
val userId = myRef.push().key
val info = Users(Feeling = "Good", Location=userLocation)
if (userId != null) {
myRef.child(userId).setValue(info)
}
}
From the Class file:
class Users(val Feeling: String, val Location: String) {
constructor() : this("","") {
}
}
</details>
# 答案1
**得分**: 1
点击监听器接收一个 view
作为参数,你可以使用它来通过其 id 来识别按钮,
val clickListener = View.OnClickListener { button ->
val feeling = when (button.id) {
R.id.button_1 -> /* 获取情感 */
R.id.button_2 -> /* ... */
...
else -> return
// 使用情感来执行您需要的操作
}
然后,您可以将此点击监听器设置给所有按钮。
编辑:
要设置点击监听器,您有不同的选项。您可以为每个按钮使用 findViewById
,使用 binding
对象然后绑定点击监听器,这取决于您的设置。
例如
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
view.findViewById<Button>(R.id.button_1).setOnClickListener(clickListener)
view.findViewById<Button>(R.id.button_2).setOnClickListener(clickListener)
}
<details>
<summary>英文:</summary>
The click listener receives a `view` as parameter, you can use that to identify the button by it's id,
val clickListener = View.OnClickListener { button ->
val feeling = when (button.id) {
R.id.button_1 -> /* get feeling */
R.id.button_2 -> /* ... */
...
else -> return
// use the feeling to do whatever you need
}
You would then set this click listener to all your buttons.
Edit:
to set the click listener, you have different options. You can use `findViewById` for each of them, using a `binding` object and then bind the click listener, it depends on your setup.
For instance
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
view.findViewById<Button>(R.id.button_1).setOnClickListener(clickListener)
view.findViewById<Button>(R.id.button_2).setOnClickListener(clickListener)
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论