我有一个由线性布局形成的活动,其中四个按钮作为子级;布局覆盖整个屏幕尺寸,按钮仅覆盖一半的屏幕尺寸(see here)。
每个按钮都有一个触摸侦听器,因此我能够同时处理所有按钮的触摸事件:例如,如果我触摸并按住按钮1,而在触摸按钮2之后,则甚至达到了按钮2的onTouch事件如果未释放按钮1。
当我按住背景(线性布局)并同时触摸其中一个按钮时,就会出现问题:onTouch事件未到达按钮;我必须释放背景上的触摸才能使按钮正常工作。
我需要用左手握住手机,并用右手按下按钮。
我如何使其工作?
编辑。如下面建议的更多详细信息。
活动代码,将侦听器分配给按钮。侦听器代码无关紧要,在糟糕的情况下,根本无法使用onTouch方法。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_keyboard);
// Setup keyboard listener
KeyListener keyListener = new KeyListener();
findViewById(R.id.key_frst).setOnTouchListener(keyListener);
findViewById(R.id.key_scnd).setOnTouchListener(keyListener);
findViewById(R.id.key_thrd).setOnTouchListener(keyListener);
findViewById(R.id.key_frth).setOnTouchListener(keyListener);
}
活动配置,在此尝试中,有一个ConstraintLayout包含一个包含四个按钮的CustomLinearLayout(请参见下面的代码)。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"
android:focusable="auto"
android:focusableInTouchMode="false"
tools:context=".KeyboardActivity">
<com.unimi.lim.hmi.ui.CustomLinearLayour
android:id="@+id/keyboard_vlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="100dp"
android:clickable="false"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<Button
android:id="@+id/key_frth"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="@string/key_frth" />
<Button
android:id="@+id/key_thrd"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="@string/key_thrd" />
<Button
android:id="@+id/key_scnd"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="@string/key_scnd" />
<Button
android:id="@+id/key_frst"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="@string/key_frst"
tools:visibility="visible" />
</com.unimi.lim.hmi.ui.CustomLinearLayour>
</androidx.constraintlayout.widget.ConstraintLayout>
CustomLinearLayout扩展了LinearLayout,它在唯一的覆盖方法之下:我试图始终将触摸事件委托给布局子对象
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// Always delegate events to child
return false;
}
谢谢, 丹妮尔
答案 0 :(得分:1)
当直接触摸 LinearLayout (在其子级之外)时, LinearLayout 会消耗流中的所有后续触摸,即使手指被拖过一个孩子。这与onInterceptTouchEvent()
返回的值无关。这是有道理的,因为孩子不会看到原始的MotionEvent.ACTION_DOWN
事件。
当在其子项外部触摸 LinearLayout 时,再用第二根手指(指针)触摸子项时, LinearLayout 仍会消耗后续操作。这也很有意义,因为第二次触摸可能是 LinearLayout 上手势的一部分。
以上均为默认设置。可以通过在自定义 LinearLayout 中编码dispatchTouchEvent()
来更改行为,方法是调用第二个指针的孩子的dispatchTouchEvent()
将孩子的触摸分配给孩子。 (如果您不需要自定义视图,也可以在活动中完成。)
我发现this有助于理解Android的触摸系统。