android - frameLaout 的 TouchListener

标签 android ontouchlistener android-framelayout

我有一个包含几个 View 的 FrameLayout。我想将 TouchListener 设置为 frameLayout,布局是在代码中创建的:

FrameLayout textLayout = new FrameLayout(getActivity());
            textLayout.setOnTouchListener(this);
            FrameLayout.LayoutParams textLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            textLayout.setLayoutParams(textLayoutParams);
            container.addView(textLayout);

我给它分配了一个 touchListener 但它没有输入。

@Override
    public boolean onTouch(View v, MotionEvent event) {
        Log.d("tag","touch");
        return true;
    }

更新:
我想我发现了部分问题:我将 frameLayout 的背景设置为绿色并扩展了 framelayout 占用的空间,这样它就不会只覆盖它的 View ,而是覆盖更多一点。所以我看到了我的观点和他们旁边的绿色。当我触摸绿色时,onTouch 事件会激活,但不会在我触摸 View 时激活。

最佳答案

看来您正在使用您的 fragment 作为监听器。请确保它实现并覆盖,即

public final MyFragment implements View.OnTouchListener {
    ....
}

然后确保您没有在返回 true 的 Activity 或其他 fragment/ View 中使用触摸监听器,即触摸事件已被消耗并且不会被调度。

注意 为了即使在 frame layout container 中有 view 也能正确派发事件,可以将它们设置为不可点击,即

<FrameLayout
    android:id="@+id/frameLayout"
    android:clickable="true"
    ...>
    <TextView android:id="@+id/text" android:clickable="false" .../>
    <... android:clickable="false" .../>
</FrameLayout>

如果需要,您也可以在代码中禁用所有 View 作为可点击对象:

text.setClickable(false);

关于android - frameLaout 的 TouchListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31245392/

相关文章:

android - 如何在用户触摸事件时在 xml 布局上 move 图像?

android - 在android中实现滑动覆盖面板的最简单方法

android - Firebase 数据库 ArrayList 未排序

android - 改造 response.errorBody() 为空

java - OnClickListener 只执行一次

android - 带圆角的 FrameLayout

android - FragmentTransaction 替换方法无法正常工作

android - intellij + gradle + robolectric + Espresso

android - 防止 WiFi-direct 在不使用时关闭

android - 附加 onTouchListener 后 ScrollView 不闪烁