Android - 设置Switch不能手动切换 只能代码切换

1.自定义SwitchCompat,,屏蔽父类的setOnCheckedChangeListener和setOnClickListene

@SuppressLint("AppCompatCustomView")
public class NotClickableSwitchCompat extends SwitchCompat {
    
    
    OnClickListener l;
    public NotClickableSwitchCompat(Context context) {
    
    
        super(context);
    }

    public NotClickableSwitchCompat(Context context, AttributeSet attrs) {
    
    
        super(context, attrs);
    }

    public NotClickableSwitchCompat(Context context, AttributeSet attrs, int defStyleAttr) {
    
    
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setOnCheckedChangeListener(@Nullable OnCheckedChangeListener listener) {
    
    
        //super.setOnCheckedChangeListener(listener);
    }
	
	@Override
    public void setOnClickListener(@Nullable OnClickListener l) {
    
    
    	//super.setOnClickListener(l);
        this.l = l;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
    
    
        if (ev.getAction() == MotionEvent.ACTION_UP){
    
    
            if (l != null){
    
    
                l.onClick(this);
            }
        }
        return true;
    }

}

2.xml文件

<com.example.lxhpdddjtrade.widget.NotClickableSwitchCompat
        android:id="@+id/switch_fingerprint"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:background="@color/content_dark_bg"
        android:textColor="@color/textBlack"
        android:text="指纹识别"
        android:visibility="visible"/>

效果:在这里插入图片描述

3.Activity

		//设置状态
        switchFingerprint.setChecked(isOpenFinger);
        switchFingerprint.setOnClickListener( v -> {
    
    
        	//点击逻辑...
        });

猜你喜欢

转载自blog.csdn.net/czssltt/article/details/124961453