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

Android自定义View组件XML布局中onClick事件无法触发求助

解决自定义View onClick事件不生效的问题

咱们一步步排查并解决你遇到的FollowSourceButton点击事件不生效的问题:

核心原因分析

你的自定义View继承自RelativeLayout,同时在init代码里inflate了一个match_parent尺寸的RelativeLayout(followButtonRView)作为子View,并且这个子View设置了android:clickable="true"。这会导致点击事件被子View优先消费,而你在XML中绑定到自定义View本身的android:onClick事件就无法触发了。

具体解决方案

方案1:移除子View的clickable属性

直接修改自定义View的布局文件follow_source_button.xml,去掉根RelativeLayout的android:clickable="true"属性:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/followButtonRView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

 <TextView 
    android:id="@+id/followSourceButton"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fontFamily="@font/droidkufi_bold"
    android:padding="0dp"
    android:text="@string/followSourceButton"
    android:textAlignment="center"
    android:textSize="14sp"
    android:visibility="gone"
    android:duplicateParentState="true"/>

 <ProgressBar 
    android:id="@+id/followButtonProgress"
    style="?android:attr/progressBarStyleSmall"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone"
    android:duplicateParentState="true"/>
</RelativeLayout>

同时保留自定义View代码里的isClickable = true,确保自定义View本身能接收点击事件。

方案2:让子View的点击事件传递给父View

如果确实需要子View保留clickable属性,可以在自定义View的init中给子RelativeLayout设置点击监听,手动触发父View的点击事件:

class FollowSourceButton(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs) {
    private var btn: TextView;
    private var progressBar: ProgressBar
    private var relativeLayout : RelativeLayout

    init {
        inflate(context,R.layout.follow_source_button,this)
        btn = findViewById(R.id.followSourceButton)
        progressBar = findViewById(R.id.followButtonProgress)
        relativeLayout = findViewById(R.id.followButtonRView)
        isClickable = true
        
        // 让子View的点击触发父View的点击事件
        relativeLayout.setOnClickListener { performClick() }
    }
}

额外检查项

  • 确保使用自定义View的布局已经正确启用Data Binding(根标签为<layout>),且sourceListeners对象不为null,onClick方法的参数类型和调用逻辑正确。
  • 检查setFollowState自定义属性的实现代码(你提供的源码里未包含这部分),确保在切换状态时没有将isClickable设置为false,否则会直接禁用点击事件。

内容的提问来源于stack exchange,提问作者Yasser-Farag

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 19:27:44