如何点击工具栏后面的视图?

时间:2015-05-24 16:33:16

标签: android android-actionbar android-support-library material-design android-toolbar

我有一个透明/半透明背景的工具栏,它覆盖了内容。因此,在工具栏后面,可以显示可单击的视图。问题是它们无法通过工具栏单击,因为工具栏正在捕获click事件。

我尝试为工具栏设置android:clickable="false"android:focusable="false"android:focusableInTouchMode="false",但它没有效果。如何通过工具栏将点击发送到基础视图?

4 个答案:

答案 0 :(得分:26)

看看Toolbar的实施情况。无论clickable属性如何,都会触摸事件

@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;
}

解决方案是从Toolbar延伸并覆盖onTouchEvent

public class NonClickableToolbar extends Toolbar {

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return false;
    }
}

答案 1 :(得分:2)

工具栏会消耗所有点击次数。您需要子类化工具栏,就像已经提到的@Matthias Robbens一样。

如果您仍希望能够在工具栏上设置点击侦听器,请使用以下命令:

/** 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;
}

答案 2 :(得分:0)

更简单的答案是:

toolbarV?.isClickable = false
toolbarV?.isFocusable = false

答案 3 :(得分:-8)

您的设计需要调整。您无法在透明/半透明工具栏后面提供可单击的视图。您需要提供一个等于工具栏高度的顶部填充和/或实现工具栏的快速返回模式。