父布局与子布局控件的实现响应点击事件冲突问题。

来源:互联网 发布:nba战报今日战报数据 编辑:程序博客网 时间:2024/05/17 06:22

布局类:

一:以RelativeLayout为例

<方法一>

1,在代码中加入如下红色代码,不然会被包含在其中的控件把焦点抢占,此时子控件无需设置clickable和focuseable

<RelativeLayout
            android:id="@+id/relativeLayout"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:onClick="onClick"

            android:clickable="true" >

            ......

</RelativeLayout>

2,一方面可以在代码中find出来,添加监听器onClickListenner,另一方面也可以添加一个onClick()方法,在activity中实现指定的方法。以后者为例。在布局中必须加上上述蓝色代码,android:onClick="onClick",其中等号右边的值,可以自定义为自己的方法,只是得在activity中提供此方法,类似onClick()。

3,activity的添加代码,如下

public void onClick(View v) {
        switch (v.getId()){
            case R.id.relativeLayout:
                System.out.println("整个布局被点击");
                break;
        }
    }

<方法二>

<RelativeLayout

            android:id="@+id/relativeLayout"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:focusableInTouchMode="true" >

            ......

</RelativeLayout>

1,在activity中find在添加OntouchLisenner方法

2,实现OntouchLisenner的Ontouch()方法

<可能出现的问题 注意!!!!!!!!!>

1,当把<RelativeLayout></RelativeLayout>嵌套在其他布局时,android:focusableInTouchMode="true"和android:clickable="true"不能同时设置。

2,当有多个<RelativeLayout></RelativeLayout>实现整体点击时,应当让activity实现OnClickListenner或OntouchListenner,不要单独的在给布局设置时new,即不要给每个布局setOnTouchListener(new ...);每个监听器都是新的很容易出现执行多次监听方法.


二 ListView


android:descendantFocusability属性的值有三种:
   beforeDescendants:viewgroup会优先其子类控件而获取到焦点
   afterDescendants:viewgroup只有当其子类控件不需要获取焦点时才获取焦点
   blocksDescendants:viewgroup会覆盖子类控件而直接获得焦点

属性一般解决lisview中嵌套按钮而出现的点击时间冲突问题。 
官方文档描述如下: 
android:descendantFocusability
Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus.
Must be one of the following constant values. 

如果遇到Listview和Button点击事件冲突就在item布局的根布局添加次属性(android:descendantFocusability),一般选afterDescendants把布局中按钮添加属性android:focusable=”false”,最后在相应地方添加按钮的点击监听事件就可以避免冲重点内容突,实现item及内部按钮都可点击不冲突的效果。 


阅读全文
0 0