Android 自定义 一个可以控制子控件是否可以点击的layout

有一个资料页面,里面包含有很多的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改一下就好了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值