一.初遇问题
在做项目的过程中遇到了一个问题,有一个可以显示两个TextView外加一个RadioButton 的ListView,然后给ListView 设置了OnItemClickListener,
mListView.setOnItemClickListener(mOnItemClickListener);
点击Listview的列表确没有任何反应,onItemClick方法中的log也没有打印。
二.分析原因
是什么导致ListView的Item点击事件失效呢?
首先我们的Item中有一个可以点击的RadioButton,大家都知道RadioButton可以点击,可以点击就涉及到焦点的获取,诸如 ImageButton、CheckBox、RadioButton之类的控件本身在初始化的时候就赋予了焦点,我们来看一下ImageButton的构造函数
public ImageButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
setFocusable(true);
}
/**
* Set whether this view can receive the focus.
*
* Setting this to false will also ensure that this view is not focusable
* in touch mode.
*
* @param focusable If true, this view can receive the focus.
*
* @see #setFocusableInTouchMode(boolean)
* @attr ref android.R.styleable#View_focusable
*/
public void setFocusable(boolean focusable) {
if (!focusable) {
setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
}
setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
}
setFlags的代码比较长这里就不再贴出来,感兴趣的同学可以自行查阅,总之这类子控件初始化后会被赋予焦点,从而抢夺父容器的焦点导致父容器点击失效。
三.解决办法
当查阅相关api可以发现
ViewGroup的api中有一个setD