在带有子级的LinearLayout上没有触发onClick

jul*_*jul 58 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>
Run Code Online (Sandbox Code Playgroud)

我的自定义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();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

Yur*_*ets 98

android:duplicateParentState="true" 没帮我

要使您的布局可以与其子项一起使用,您需要为每个项添加此选项:

 android:clickable="false"
Run Code Online (Sandbox Code Playgroud)

然后点击操作会.

  • 谢谢@Yurets它的工作就像魔法一样.这一定是可以接受的答案 (3认同)

Bla*_*elt 58

为每个孩子

机器人:duplicateParentState = "真"

  • 谢谢你!解决了我今天使用嵌套线性布局选择的问题. (3认同)
  • 感谢这样做,解决了我类似的问题,即我有多个控件要表达“被单击”的视觉状态,而只需要在父级中处理事件。 (2认同)

ele*_*yle 20

这不是你的情况,但我有类似的可点击问题ViewGroup.寻找解决方案小时后发现,我设置android:inputTypeTextView我的里面ViewGroup这是阻止onClick()监听器(不知道为什么)

不要android:inputType与TextView一起使用

  • 这也是我的问题,请确保您没有inputType或将其设置为none!感谢发布此内容 (2认同)

nho*_*ass 5

android:duplicateParentState="true"使我的TextView看起来像是被禁用了,并且无法接收点击事件。

您所需要的只是设置TextView clickable="false"。所以点击事件将分派到父布局,并且TextView仍然可以对触摸事件做出反应(具有涟漪效应)。


Aha*_*kat 5

使您的父级LinearLayout的android:clickable =“ true”

使所有childview的android:clickable =“ false”

在Linearlayout下- 从TextView中删除android:inputType =“”