有時候需要控制一個佈局下所有子view是否可以Click、Touch,例如不讓佈局下的SeekBar、Button等響應拖動和點擊事件。
可以通過事件攔截簡單實現,在父佈局中對事件進行攔截,那麼其子view將不會獲得Touch事件,也就無法響應Click和Touch了,對SeekBar而言則無法拖動、Button而言則無法點擊。
package com.dway.test;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;
public class MyLayout extends RelativeLayout {
private boolean mChildViewsCanTouch = true;
public MyLayout(Context context) {
super(context);
}
public MyLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* 設置該佈局的所有子view是否能響應手勢事件,例如touch、click
* @param canTouch
*/
public void setChildViewsCanTouch(boolean canTouch){
mChildViewsCanTouch = canTouch;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//事件攔截,返回true則攔截事件傳遞給子控件,即子控件無法進行touch和click等
return !mChildViewsCanTouch || super.onInterceptTouchEvent(ev);
}
}
使用也很簡單:
myLayout.setChildViewsCanTouch(true);//允許子view獲得Touch事件
myLayout.setChildViewsCanTouch(false);//禁止子view獲得Touch事件