您的位置:首页 > 移动开发 > Android开发

[Android界面] GridView 中含有两个以上的Button时Item点击事件没有效果

2014-08-22 11:34 567 查看
开发中很常见的一个问题,项目中的listview或者GridView 不仅仅是简单的文字,常常需要自己定义item,自己的Adapter去继承BaseAdapter,在adapter中按照需求进行编写,问题就出现了,可能会发生点击每一个item的时候没有反应,无法获取的焦点。原因多半是由于在你自己定义的Item中存在诸如ImageButton,Button,CheckBox等子控件(也可以说是Button或者Checkable的子类控件),此时这些子控件会将焦点获取到,所以常常当点击item时变化的是子控件,item本身的点击没有响应。

例如:





这时候就可以使用descendantFocusability来解决啦,API描述如下:


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.



该属性是当一个为view获取焦点时,定义viewGroup和其子控件两者之间的关系。

属性的值有三种:

beforeDescendants:viewgroup会优先其子类控件而获取到焦点

afterDescendants:viewgroup只有当其子类控件不需要获取焦点时才获取焦点

blocksDescendants:viewgroup会覆盖子类控件而直接获得焦点



通常我们用到的是第三种,即在Item布局的根布局加上android:descendantFocusability=”blocksDescendants”的属性

还有 记得 在点击的控件里面加上

android:clickable="false"
            android:focusable="false"


Item的代码为:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bind_border"
android:descendantFocusability="blocksDescendants"
android:gravity="center_horizontal"
android:orientation="vertical" >

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<com.customWidget.RoundedCornerImageView
android:id="@+id/product_item_product_icom"
android:layout_width="120dp"
android:layout_height="140dp"
android:scaleType="fitXY"
android:src="@drawable/demoproduct" />

<ImageButton
android:id="@+id/product_del_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/login_close_button"
android:clickable="false" android:focusable="false" />
</LinearLayout>

<TextView
android:id="@+id/tv_name"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="关节回复基本准则"
android:textStyle="normal|italic" />

<TextView
android:id="@+id/btn_cart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/mybutton"
android:focusable="false"
android:padding="8dp"
android:text="放入购物车" />

</LinearLayout>


Ok啦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐