有一个禁用的 onClick?

2022-09-01 21:50:27

我希望能够响应已禁用开关上的单击事件,这可能吗?

我有一个开关,直到用户填写一些信息才启用,所以它看起来像这样:

enter image description here

我想提示用户填写信息,如果他们点击禁用的开关与对话框,如下所示:

 mySwitch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (!userInfo.isFilled){
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("Fill out info first!")
                        .setMessage("You must first fill out info before turning on this featurel")
                        .setNeutralButton("Okay", null)
                        .show();
            }
        }
    });

但是,当我单击禁用的开关时不会触发,那么当用户单击它时,我该如何获得?onClick()


答案 1

您可以将透明放在 的顶部,并在 Switch 的对面切换其启用状态,并在单击此覆盖时显示该消息。ViewSwitchView


答案 2

视图.java源代码,

public boolean dispatchTouchEvent(MotionEvent event) {
    // If the event should be handled by accessibility focus first.
    if (event.isTargetAccessibilityFocus()) {
        // We don't have focus or no virtual descendant has it, do not handle the event.
        if (!isAccessibilityFocusedViewOrHost()) {
            return false;
        }
        // We have focus and got the event, then use normal event dispatch.
        event.setTargetAccessibilityFocus(false);
    }

    boolean result = false;

    if (mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onTouchEvent(event, 0);
    }

    final int actionMasked = event.getActionMasked();
    if (actionMasked == MotionEvent.ACTION_DOWN) {
        // Defensive cleanup for new gesture
        stopNestedScroll();
    }

    if (onFilterTouchEventForSecurity(event)) {
        //noinspection SimplifiableIfStatement
        ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnTouchListener != null
                && (mViewFlags & ENABLED_MASK) == ENABLED
                && li.mOnTouchListener.onTouch(this, event)) {
            result = true;
        }

        if (!result && onTouchEvent(event)) {
            result = true;
        }
    }

    if (!result && mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
    }

    // Clean up after nested scrolls if this is the end of a gesture;
    // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
    // of the gesture.
    if (actionMasked == MotionEvent.ACTION_UP ||
            actionMasked == MotionEvent.ACTION_CANCEL ||
            (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
        stopNestedScroll();
    }

    return result;
}

启用的标志可确保使用未处理的事件,但不会传递给侦听器,从而绕过所有可能的代码。因此,无法侦听禁用视图上的事件。

也就是说,您的选择是,

  1. 更改样式以模仿此处提到的禁用视图的样式,然后添加所需的功能。
  2. 添加叠加不可见视图以执行所需的功能,一旦启用视图,即可将其设置为 Gone。
  3. 使用除已启用之外的内容(您可以并且使用触摸事件)setClickable(false)