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

Android:ListView中嵌入GridView,处理点击事件的冲突

2015-05-13 15:51 591 查看
【问题】当GridView嵌入ListView后,始终响应的是GridView的点击事件,我需要的是获取到ListView的点击事件!

  在使用ListView的时候,我们使用adapter中画我们自定义item项时,一般会加上Button事件,或者Imagebutton,但是效果却不是我们想象的那么简单,因为你会发现ListView的itemclick事件就不生效了,原因很简单Button的onClick事件抢占了ListView的itemclick,我们只需在布置文件中添加下述代码屏蔽Button的onClick事件的焦点即可:

  在list的配置xml的根节点添加属性android:descendantFocusability="blocksDescendants",还有就是在要添加事件的控件上加android:focusable="false"。

  我们看看

  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.

  ConstantValueDescriptionbeforeDescendants0The ViewGroup will get focus
before any of its descendants.afterDescendants1The ViewGroup will get focus only if none of its descendants want it.blocksDescendants2The ViewGroup will block its descendants from receiving focus

  最后一个是ViewGroup将阻止其后代接收焦点

  所以 如果Listview中想不被屏蔽OnItemClickListener事件的话 那么久在item中的布局中 的最顶层布局加入这句话

  想要阻止哪个widget 就在哪个widget设置focusable="false"

  【解决问题了:】

  最近做项目,用到了listview的item的一些问题,现在抽空把它们总结一下:

  转载请表明出处:/article/1393517.html

  1、如果listview的item中有button,checkbox的时候,往往如果不做处理的情况,button,checkbox会获得焦
点,导致listview不相应OnItemLongClickListener()这个方法,抢占了Item的获得焦点的能力,解决的办法有两种:

  (1)在button,checkbox的xml布局文件中添加代码:

  android:focusable=“false”

  即就可以相应OnItemLongClickListener()这个方法了。

  (2)在listview中的item的布局文件中,在总的LinearLayout的属性中添加一句话:

  android:descendantFocusability="blocksDescendants"

  即把在LinearLayout里面的focusable属性都设置成了false,

  就可以相应OnItemLongClickListener()这个方法了。

  2、在ListView的item中有GridView,抢占焦点的情况,解决办法步骤如下:

  (1) 现在ListView的Item的最外面的LinearLayout中设置:、

  android:descendantFocusability="blacksDescendants"

  (2) 再在gridview的getView()方法中设置:

  gridview.setClickable(false);

  gridview.setPressed(false);

  gridview.setEnabled(false);

  即就可以相应OnItemLongClickListener()这个方法了。

注意:如果ListView和GridView都需要焦点时,不要在代码中加入上述setXxx(false)即可以实现。

  3、如果在布局文件中有一个或多个GridView,如果在item的布局中加入了ScrollView,如果不对gridview的item设置高度的话,这个滚动的效果只是在GridView中体现,而不在整个listview布局中体现,要想在整个布局中有上下滚动的效果,就需要设置gridview中的item的高度进行设置。具体代码可以参考下面的:

  [java] view plaincopyprint?

   gv.setNumColumns(7);

  fra = new FilterResultAdapter(mainActivity,mainActivity,AL);

  //动态设置GridView的高度

  LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams)
gv.getLayoutParams(); // 取控件mGrid当前的布局参数

  if(fra.getCount() % 7 != 0){

  linearParams.height = (Math.round(fra.getCount()/7 + 1))*34+20;// 设置高度

  }

  else{

  linearParams.height = (Math.round(fra.getCount()/7))*34+20;// 设置高度

  }

  gv.setLayoutParams(linearParams); // 使设置好的布局参数应用到控件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐