Ran into similiar problem where I needed to close expanded list elements when empty space is clicked. Here is how I solved it.
public class CustomListView extends ListView {
private OnNoItemClickListener mOnNoItemClickListener;
public interface OnNoItemClickListener {
void onNoItemClicked();
}
public CustomListView(Context context) {
super(context);
}
public CustomListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//check whether the touch hit any elements INCLUDING ListView footer
if(pointToPosition((int) (ev.getX() * ev.getXPrecision()),
(int) (ev.getY() * ev.getYPrecision())) == -1 && ev.getAction() == MotionEvent.ACTION_DOWN) {
if(mOnNoItemClickListener != null) {
mOnNoItemClickListener.onNoItemClicked();
}
}
return super.dispatchTouchEvent(ev);
}
public void setOnNoItemClickListener(OnNoItemClickListener listener) {
mOnNoItemClickListener = listener;
}
}
Then use this CustomListView in your XML file instead of regular ListView and implement OnNoItemClickListener inside your activity / fragment and call mListView.setOnNoItemClickListener(this); in onCreate to enable callback to onNoItemClicked() function.
Note that if your ListView has headers or footers then these are considered as list elements and the onNoItemClicked() won't be called.
setOnClickListener()
restriction lifted, as you make an excellent point: code.google.com/p/android/issues/detail?id=59559 – Ethelethelbert