2016-07-23 117 views
0

我视图层次在我的布局之一,如下所示(简化XML使问题清晰):如何为父容器和所有子项添加一个点击侦听器?

<LinearLayout 
    android:id="@+id/top_container" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 
     <LinearLayout 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:orientation="horizontal" 
       android:layout_marginLeft="10dp" 
       android:layout_marginRight="10dp" 
       android:layout_marginBottom="8dp" 
       > 
       // 2 childern here 
     </LinearLayout> 
     <RelativeLayout 
      android:id="@+id/inner_layout" 
      android:layout_width="match_parent" 
      android:layout_marginLeft="10dp" 
      android:layout_marginRight="10dp" 
      android:layout_marginTop="10dp" 
      android:layout_height="180dp" 
      > 
      // children here 
     </RelativeLayout> 
</LinearLayout> 

我想在该视图中的任何地方点击做一个动作。
top_container上添加点击侦听器是行不通的,除非我在顶部的某个地方点击它,而不触摸任何子视图。
有没有办法做到这一点,而不需要添加一个点击侦听器到所有的孩子(这将调用相同的处理程序)?

更新:
结束语在FrameLayout里都没有解决这个问题。如果我在RelativeLayout的任意位置单击鼠标点击监听器仍然没有解雇

+1

您是否正在为您的子视图编写任何点击侦听器? – Drv

+0

@Drv:你说得对。在其中一个子视图中有一个点击监听器。写作答案,我会接受它 – Jim

+0

@Jim是不是我的答案符合你的要求? – Divers

回答

1

裹一切RelativeLayout,并把空的FrameLayout首先您的看法,如:

<RelativeLayout> 
     <Your views....> 

     <FrameLayout 
     android:id="@+id/top_layer" 
     android:layout_width="match_parent" 
     android:layout_height ="match_parent"/> 

    </RelativeLayout> 

and then: 

findViewById(R.id.top_layer).setOnClickListener(....)

在情况下,如果你” d喜欢在下图层上传递点击事件(对您的意见),您可以使用addOnItemTouchListener而不是ClickListener

相关问题