rxbinding并点击右侧可绘制

时间:2017-06-10 06:30:14

标签: textview rx-java rx-java2 rx-binding

有没有办法使用RxBinding在EditText的右侧drawable上实现on click侦听器?

我发现的唯一一件事就是:

     RxTextView.editorActionEvents(mEditText).subscribeWith(new DisposableObserver<TextViewEditorActionEvent>() {
        @Override
        public void onNext(TextViewEditorActionEvent textViewEditorActionEvent) {
            int actionId = textViewEditorActionEvent.actionId();
            if(actionId == MotionEvent.ACTION_UP) {
            }

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    });

但在这种情况下,我无法找到有关点击位置的信息。

这是我使用RxJava的方式:

public Observable<Integer> getCompoundDrawableOnClick(EditText editText, int... drawables) {
    return Observable.create(e -> {
        editText.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                for (int i : drawables) {
                    if (i == UiUtil.COMPOUND_DRAWABLE.DRAWABLE_RIGHT) {
                        if (event.getRawX() >= (editText.getRight() - editText.getCompoundDrawables()[i].getBounds().width())) {
                            e.onNext(i);
                            return true;
                        }
                    }
                }
            }
            // add the other cases here
            return false;

        });
    });

但我觉得我正在重新发明轮子

1 个答案:

答案 0 :(得分:1)

您正在错误的位置搜索,如果您需要检查触摸事件,请使用View使用基本RxView触摸事件,然后应用您的逻辑并过滤掉所有不需要的内容感动,点击&#39;在您想要的位置(复合绘图)。
我必须承认,我不确定我是否理解for循环逻辑,你可以直接使用UiUtil.COMPOUND_DRAWABLE.DRAWABLE_RIGHT,但无论如何都遵循你的逻辑:

public Observable<Object> getCompoundDrawableOnClick(EditText editText, int... drawables) {
        return RxView.touches(editText)
                .filter(motionEvent -> {
                    if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                        for (int i : drawables) {
                            if (i == UiUtil.COMPOUND_DRAWABLE.DRAWABLE_RIGHT) {
                                if (motionEvent.getRawX() >= (editText.getRight() - editText.getCompoundDrawables()[i].getBounds().width())) {
                                    return true;
                                }
                            }
                        }
                    }
                    return false;
                })
                .map(motionEvent -> {
                    // you can omit it if you don't need any special object or map it to 
                    // whatever you need, probably you just want click handler so any kind of notification Object will do.
                });
    }