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

Kotlin安卓开发:两个按钮点击触发同一响应问题求助

问题分析与解决方案

嘿,我一眼就瞅出问题所在了——你的两个按钮控件完全重叠在一起了!

问题根源

你用了RelativeLayout作为父容器,但里面的两个LinearLayout(也就是你的自定义按钮)没有设置任何定位属性(比如layout_alignParentLeft、layout_toRightOf这类)。在RelativeLayout里,子控件默认都会堆叠在左上角,后面添加的控件会覆盖在前面的控件之上。所以你的custom_button_uk其实完全盖在了custom_button_cn的上方,不管你点击哪个视觉区域,实际触发的都是上层的custom_button_uk,这就是为什么日志里全是ENGLISH的原因。

修复步骤

只需要给两个LinearLayout添加位置属性,让它们分开显示就行,比如让它们左右并排:

<RelativeLayout 
    android:id = "@+id/rel_lay"
    android:layout_width="1280dp"
    android:layout_height="1280dp"
    android:layout_marginTop="35pt" >

    <LinearLayout
        android:id="@+id/custom_button_cn"
        android:layout_width="400dp"
        android:layout_height="400dp"
        android:background="@drawable/china_button_drawable"
        <!-- 让中文按钮靠左对齐,添加边距避免贴边 -->
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="80dp">

        <ImageView
            android:layout_width="400dp"
            android:layout_height="400dp"
            android:src="@drawable/button_cn" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/custom_button_uk"
        android:layout_width="400dp"
        android:layout_height="400dp"
        android:background="@drawable/uk_button_drawable"
        <!-- 让英文按钮靠右对齐,添加边距避免贴边 -->
        android:layout_alignParentRight="true"
        android:layout_marginRight="80dp">

        <ImageView
            android:layout_width="400dp"
            android:layout_height="400dp"
            android:src="@drawable/button_en" />
    </LinearLayout>

</RelativeLayout>

额外确认

你的代码逻辑本身是没问题的——setOnClickListener(this)和onClick里的when分支都写对了,只要布局里的控件不重叠,点击事件就能正确触发对应的分支。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:14:31