【问题标题】:How to click views behind a Toolbar?如何点击工具栏后面的视图?
【发布时间】:2015-08-06 04:38:36
【问题描述】:
我有一个覆盖内容的透明/半透明背景的工具栏。因此,在工具栏后面,可以出现可点击的视图。问题是无法通过工具栏点击它们,因为工具栏正在捕获点击事件。
我尝试为工具栏设置android:clickable="false"、android:focusable="false"和android:focusableInTouchMode="false",但没有效果。如何通过工具栏将点击发送到底层视图?
【问题讨论】:
标签:
android
android-actionbar
android-support-library
material-design
android-toolbar
【解决方案1】:
看看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;
}
}
【解决方案2】:
工具栏消耗所有点击。您需要将 Toolbar 子类化,就像已经提到的@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;
}
【解决方案3】:
更简单的答案是:
toolbarV?.isClickable = false
toolbarV?.isFocusable = false
【解决方案4】:
您的设计需要调整。您不能在透明/半透明工具栏后面提供可点击的视图。您需要提供与工具栏高度相等的顶部填充和/或实现工具栏的快速返回模式。