How to click views behind a Toolbar?

前端 未结 4 1062
长发绾君心
长发绾君心 2021-01-04 07:09

I have a toolbar with a transparent/translucent background that overlays the content. So, behind the toolbar, views can appear that are clickable. The problem is that they c

相关标签:
4条回答
  • 2021-01-04 07:27

    Easier answer would be just :

    toolbarV?.isClickable = false
    toolbarV?.isFocusable = false
    
    0 讨论(0)
  • 2021-01-04 07:27

    Your design needs to be adjusted. You cannot provide clickable views behind a transparent/translucent toolbar. You need to provide a top padding equal to the height of the toolbar and/or implement the quick return pattern for the toolbar.

    0 讨论(0)
  • 2021-01-04 07:32

    Take a look at the implementation of Toolbar. It eats touch events, regardless of the clickable attribute.

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // Toolbars always eat touch events, but should still respect the touch event dispatch
        // contract. If the normal View implementation doesn't want the events, we'll just silently
        // eat the rest of the gesture without reporting the events to the default implementation
        // since that's what it expects.
    
        final int action = MotionEventCompat.getActionMasked(ev);
        if (action == MotionEvent.ACTION_DOWN) {
            mEatingTouch = false;
        }
    
        if (!mEatingTouch) {
            final boolean handled = super.onTouchEvent(ev);
            if (action == MotionEvent.ACTION_DOWN && !handled) {
                mEatingTouch = true;
            }
        }
    
        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
            mEatingTouch = false;
        }
    
        return true;
    }
    

    The solution is to extend from Toolbar and override onTouchEvent.

    public class NonClickableToolbar extends Toolbar {
    
        @Override
        public boolean onTouchEvent(MotionEvent ev) {
            return false;
        }
    }
    
    0 讨论(0)
  • 2021-01-04 07:32

    Toolbar consumes all clicks. You need to subclass Toolbar, like @Matthias Robbens already mentioned.

    If you still want to be able to set a click listener on the toolbar, use this:

    /** Do not eat touch events, like super does. Instead map an ACTION_DOWN to a click on this 
     * view. If no click listener is set (default), we do not consume the click */
    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN || ev.getAction() == MotionEvent.ACTION_POINTER_DOWN){
            return performClick();
        }
    
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题