You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin按钮点击无响应:同逻辑在其他布局可正常运行

问题描述

我有一个能正常将用户添加到Firebase Realtime Database的注册页面,但修改参数适配新布局后,NewProperty页面的按钮点击事件未被识别,无法将房产数据推送到数据库的properties节点中。相关代码、布局XML、数据库规则及结构如下:

Kotlin代码

class NewProperty : AppCompatActivity() {
    
        private lateinit var auth: FirebaseAuth
        private lateinit var dbRef: DatabaseReference
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_new_property)
    
            auth = Firebase.auth
    
            dbRef = FirebaseDatabase.getInstance().getReference("properties")
    
            val createPropertyButton: Button = findViewById(R.id.btn_newProperty)
            createPropertyButton.setOnClickListener {
                CreateNewProperty()
            }
        }
private fun CreateNewProperty() {

        // TODO add trim
        val name = findViewById<EditText>(R.id.input_propertyName).text.toString()
        val address = findViewById<EditText>(R.id.input_address).text.toString()
        val city = findViewById<EditText>(R.id.input_city).text.toString()
        val state = findViewById<EditText>(R.id.input_state).text.toString()
        val zip = findViewById<EditText>(R.id.input_zip).text.toString()
        val bed = findViewById<EditText>(R.id.textAddBed).text.toString()
        val bath = findViewById<EditText>(R.id.textAddBath).text.toString()
        val living = findViewById<EditText>(R.id.textAddLiving).text.toString()
        val dining = findViewById<EditText>(R.id.textAddDining).text.toString()
        val closet = findViewById<EditText>(R.id.textAddCloset).text.toString()
        val oArea = findViewById<EditText>(R.id.textOwnerAreas).text.toString()
        val fire = findViewById<Chip>(R.id.hasFireplace).isChecked
        val shed = findViewById<Chip>(R.id.hasShed).isChecked
        val fPorch = findViewById<Chip>(R.id.hasFrontPorch).isChecked
        val bPatio = findViewById<Chip>(R.id.hasBackPatio).isChecked
        val sprinkler = findViewById<Chip>(R.id.hasSprinklerSystem).isChecked
        val flower = findViewById<Chip>(R.id.hasFlowerbeds).isChecked
        val fence = findViewById<Chip>(R.id.hasFence).isChecked

        // val rG = findViewById<RadioGroup>(R.id.accountType_signup)
        // val uType = findViewById<RadioButton>(rG!!.checkedRadioButtonId).text.toString()


       if (name.isEmpty() || address.isEmpty() || city.isEmpty() || state.isEmpty() || zip.isEmpty()) {
            Toast.makeText(
                this, "Please fill in all Fields.",
                Toast.LENGTH_SHORT
            ).show()
            return
        }

        val pId = dbRef.push().key!!
        val p = Property(
            pId,
            name,
            address,
            city,
            state,
            zip,
            bed,
            bath,
            living,
            dining,
            closet,
            oArea,
            fire,
            shed,
            fPorch,
            bPatio,
            sprinkler,
            flower,
            fence
        )
        // save property to database
            dbRef.child(pId).setValue(p)
                .addOnCompleteListener {
                    val intent = Intent(this, MainActivity::class.java)
                    startActivity(intent)
                    
                    Toast.makeText(
                        baseContext, "Property Data Saved",
                        Toast.LENGTH_SHORT
                    ).show()
                }
                .addOnFailureListener {
                    // If other errors happen, display error as received
                    Toast.makeText(
                        this, "An Error Occurred: ${it.localizedMessage}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
        }

布局XML

<TextView
        android:id="@+id/textPropertySetup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginTop="64dp"
        android:ems="10"
        android:text="Property Information"
        android:textSize="24sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ScrollView
        ...
    </ScrollView>

    <Button
        android:id="@+id/btn_newProperty"
        android:layout_width="250dp"
        android:layout_height="50dp"
        android:layout_marginBottom="96dp"
        android:text="SUBMIT"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:visibility="visible" />

    <Button
        android:id="@+id/btn_cancelAddProperty"
        android:layout_width="250dp"
        android:layout_height="50dp"
        android:layout_marginBottom="32dp"
        android:text="nevermind"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Firebase数据库规则

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

数据库结构

https://... .firebaseio.com/
users
-N8RGm9rvZ4oYT1o6u8D
-N8RGodvlrjsQEKPz8Fe
-N8RJZxcM4kFUehhgPc5
-N8RLX8tIfQSaydVMWjv
-N8W89_gkgvQ3TrC41Vx
-N8W98Wcxx4djKMooZ9n
-N8WBHJ_caGlOD74gsPI
-N8WaHXNKgCMyCM5J4q8
-N8aPsZPrFxvYp0szQr9

目前properties节点无数据,无法成功推送。


解决方案

一、先排查按钮点击事件未触发的问题

  1. 检查按钮是否被遮挡
    布局中ScrollView的属性被省略,大概率是它覆盖了btn_newProperty按钮,导致点击事件无法触发。给ScrollView添加底部约束,确保它不会覆盖按钮:

    <ScrollView
        ...
        app:layout_constraintBottom_toTopOf="@id/btn_newProperty" />
    

    或者调整ScrollView的layout_marginBottom,让它和按钮之间留出足够空间。

  2. 验证按钮ID是否匹配
    确认findViewById(R.id.btn_newProperty)中的ID和布局里的按钮ID完全一致,没有拼写错误。

  3. 添加日志排查点击事件
    在setOnClickListener中添加日志,确认点击是否被触发:

    createPropertyButton.setOnClickListener {
        Log.d("NewProperty", "Submit button clicked")
        CreateNewProperty()
    }
    

    运行后查看Logcat,如果没有日志输出,说明点击事件确实没绑定成功;如果有日志,问题出在CreateNewProperty方法内部。

二、排查数据无法推送的问题(如果点击事件已触发)

  1. 检查Property类的序列化
    Firebase Realtime Database要求实体类必须满足:

    • 有无参构造函数
    • 所有字段的getter方法(或字段为public)
      确保你的Property类符合要求,示例:
    data class Property(
        val pId: String? = null,
        val name: String? = null,
        val address: String? = null,
        // 其他字段...
        val fence: Boolean? = null
    ) {
        // 无参构造函数,Firebase需要
        constructor() : this(null, null, null, ..., null)
    }
    
  2. 检查Firebase初始化
    确认项目已正确配置Firebase,google-services.json文件已放置在app目录下,且依赖已正确添加:

    // 项目级build.gradle
    dependencies {
        classpath 'com.google.gms:google-services:4.4.1'
    }
    
    // app级build.gradle
    plugins {
        id 'com.google.gms.google-services'
    }
    
    dependencies {
        implementation 'com.google.firebase:firebase-database:20.3.0'
        implementation 'com.google.firebase:firebase-auth:22.3.1'
    }
    
  3. 检查网络连接
    确保测试设备有稳定的网络连接,Firebase需要网络才能推送数据。

  4. 查看Firebase控制台日志
    登录Firebase控制台,进入Realtime Database的“规则”标签页,查看“监控”中的日志,是否有写入失败的记录,能帮你定位具体错误。

三、额外优化建议

  • 避免在CreateNewProperty中重复调用findViewById,可以在onCreate中一次性初始化所有输入控件,提升性能。
  • 给输入框添加trim()处理,避免用户输入的空格导致判断为空:
    val name = findViewById<EditText>(R.id.input_propertyName).text.toString().trim()
    

内容的提问来源于stack exchange,提问作者Shane Weber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 07:33:20