我有一个覆盖内容的透明/半透明背景的工具栏。所以,在工具栏后面,可以看到可点击的视图。问题是无法通过工具栏单击它们,因为工具栏正在捕获单击事件。如何点击工具栏后面的视图?
我试着为工具栏设置android:clickable="false"
,android:focusable="false"
和android:focusableInTouchMode="false"
,但它没有效果。我如何通过工具栏将点击发送到底层视图?
我有一个覆盖内容的透明/半透明背景的工具栏。所以,在工具栏后面,可以看到可点击的视图。问题是无法通过工具栏单击它们,因为工具栏正在捕获单击事件。如何点击工具栏后面的视图?
我试着为工具栏设置android:clickable="false"
,android:focusable="false"
和android:focusableInTouchMode="false"
,但它没有效果。我如何通过工具栏将点击发送到底层视图?
看看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;
}
}
您的设计需要调整。您无法在透明/半透明工具栏后面提供可点击的视图。您需要提供与工具栏高度相等的顶部填充和/或实现工具栏的快速返回模式。
工具栏消耗所有的点击。您需要继承工具栏,就像已经提到的@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;
}