有一个资料页面,里面包含有很多的edittext和CheckBox之类的控件
要求是 平时不可以编辑,在用户按了右上角的编辑按钮后才可以编辑
这样的页面如果对每个控件设定enabled属性是可以控制的,但是太麻烦了.
参考了网上以为朋友的代码,改动了一下之后可以达到
1.在xml页面就可以设定是否允许子控件点击
2.在代码页面也可以自由控制子控件点击
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;
/**
* Created by ppg on 17-6-11.
* 可以直接控制所有子控件是否可点击的LinearLayout
*/
public class EnableChildClickLinearLayout extends LinearLayout {
//子控件是否可以接受点击事件
private boolean childClickable = true;
public EnableChildClickLinearLayout(Context context) {
this(context, null);
}
public EnableChildClickLinearLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public EnableChildClickLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(AttributeSet attrs) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.EnableChildClickLinearLayout);
childClickable = typedArray.getBoolean(R.styleable.EnableChildClickLinearLayout_Clickable, true);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//返回true则拦截子控件所有点击事件,如果childclickable为true,则需返回false
return !childClickable;
}
public void setChildClickable(boolean clickable) {
childClickable = clickable;
}
}
在values/attrs复制以下代码
<declare-styleable name="EnableChildClickLinearLayout">
<attr name="Clickable" format="boolean"/>
</declare-styleable>
这样
childClickable=typedArray.getBoolean(R.styleable.EnableChildClickLinearLayout_Clickable, true);
就可以在xml页面设置属性了
<com.xxxxx.xxxx.views.EnableChildClickLinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:Clickable="false">
这个例子是LinearLayout,但是可以退广到所有的viewgroup的子类,包括FrameLayout和RelativeLayout,只要extends LinearLayout改一下就好了