android - onClick 未在带有子项的 LinearLayout 上触发

标签 android onclick android-linearlayout

我有一个带有较小 TextView 子项的自定义 LinearLayout。我希望能够单击 TextView 未覆盖的区域,因此我将 clickable=true 和一个 onclicklistener 设置为 LinearLayout,但不会触发 onClick。如果我在 TextView 上设置 onclick 监听器,它会按预期工作......

有人可以帮忙吗?

ar_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ar_item" android:layout_width="202dp"
    android:layout_height="62dp" android:background="@drawable/bg_item_ar"
    android:clickable="true">

    <TextView android:id="@+id/ar_item_txt"
        android:layout_width="164dp" android:layout_height="fill_parent"
        android:paddingBottom="8dp" android:paddingLeft="8dp"
        android:paddingTop="8dp" android:paddingRight="6dp" android:gravity="center"
        android:background="#50000000" />

</LinearLayout>

我的自定义线性布局

public class ARView extends LinearLayout
{    

    public ARView(final Context context, String name, String id)
    {        
        super(context);  
        getLayoutInflater().inflate(R.layout.ar_item, this ,true);
        LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
        inflater.inflate(R.layout.ar_item, null);

        TextView textView = (TextView) findViewById(R.id.ar_item_txt);
        textView.setText(name);

        setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {                   
                Toast t = Toast.makeText(context, "hey!", Toast.LENGTH_SHORT);
                t.show();
            }
        });
    }
}

最佳答案

android:duplicateParentState="true" 没有帮助我。

为了让你的布局可以点击它的子元素,你需要为每个子元素添加这个选项:

 android:clickable="false"

然后点击处理将向上父级

关于android - onClick 未在带有子项的 LinearLayout 上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6763876/

相关文章:

android - android studio 底部工具栏中的运行选项卡已消失

java - 获取选定的回收 View 的文本(使用 FireBase)

Android 全屏应用太暗

javascript - 我应该将 H1 转换为按钮以让它调用函数吗?

android - WebViews 的 ListView - 重复使用不同高度的项目失败;在显示任何 View 之前询问所有 View

安卓工作室 : Android Device Monitor not showing my device

javascript 代码与 jquery 一起放置时不起作用

javascript - 如何防止调用 jQuery 函数

android - 以编程方式设置 ImageButton layout_gravity

android - 尝试将 View 动态添加到线性布局android时获取java.lang.RuntimeException