需求是這樣的:
封裝了一個(gè)View
抛蚁,類似這樣:
image.png
1
處的view
是添加進(jìn)來的,需要在點(diǎn)了1
里面的某個(gè)view
之后风科,把整個(gè)view
隱藏掉。因?yàn)?code>1處的
view
是添加進(jìn)來的给郊,它里面的子view
的點(diǎn)擊事件都寫在它的類里面的整胃,外部不知道有沒有被點(diǎn)擊赋秀,也就沒法隱藏整個(gè)view
杠愧。
思路:利用view
的OnTouchListener
配合GestureDetector
來通知是否被點(diǎn)擊了
- 如果這個(gè)
view
是ViewGroup
待榔,遍歷所有的子view
,判斷子view
和自身是否有點(diǎn)擊事件和是否顯示
private void setGesture(ViewGroup viewGroup){
if(viewGroup.hasOnClickListeners() && viewGroup.getVisibility() == VISIBLE){
viewGroup.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return detector.onTouchEvent(event);//一定要返回false殴蹄,否則會(huì)攔截onClick事件
}
});
}
for(int i = 0;i<viewGroup.getChildCount();i++){
View view = viewGroup.getChildAt(i);
if(view instanceof ViewGroup){
setGesture((ViewGroup) view);
continue;
}
if(view.hasOnClickListeners() && view.getVisibility() == VISIBLE){
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return detector.onTouchEvent(event); //一定要返回false究抓,否則會(huì)攔截onClick事件
}
});
}
}
}
- 如果是
view
就跳過遍歷子view
這一步
配合GestureDetector
:
detector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onSingleTapConfirmed(MotionEvent e) { //單擊
if(onViewClick!= null){
onViewClick.onClick(null);
}
return super.onSingleTapConfirmed(e);
}
});