【问题标题】:OnClickListener triggered for all Custom Views inside a FrameLayout为 FrameLayout 内的所有自定义视图触发 OnClickListener
【发布时间】:2018-05-02 02:28:06
【问题描述】:

我正在以编程方式将自定义视图添加到 FrameLayout:

public class CustomView extends View {
 ....
    @Override
    protected void onDraw(Canvas canvas) {
       ... //Doing stuff here 
    }
}

--

containerLayout = (FrameLayout) findViewById(R.id.container_layout);

CustomView cv1 = new CustomView(ctx);
CustomView cv2 = new CustomView(ctx);

cv1.setOnClickListener(new OnClickListener({
 Toast.makeText(ThisActivity.this, "FooBar", Toast.LENGTH_LONG).show();
});

cv2.setOnClickListener(new OnClickListener({
 Toast.makeText(ThisActivity.this, "BlaBlub", Toast.LENGTH_LONG).show();
});

container_layout.addView(cv1);
container_layout.addView(cv2);

现在,当我点击自定义视图时,两个自定义视图都会触发事件,而不仅仅是我点击的那个。我可以一个接一个地看到两个吐司。任何想法为什么?

更新 1 - 更多详情 我正在开发一个 AR 应用程序,我尝试根据运行良好的位置数据 (GPS) 集成视图。唯一不起作用的是我的自定义视图的侦听器。我可以在 CameraView/SurfaceView 中看到我的两个自定义视图,它们不在同一位置

    <FrameLayout
    android:id="@+id/container_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.cameraview.CameraView
        android:id="@+id/camera_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:keepScreenOn="true"
        android:adjustViewBounds="true"
        app:autoFocus="true"
        app:aspectRatio="4:3"
        app:facing="back"
        app:flash="off"/>

    <SurfaceView
        style="@style/ThemeOverlay.AppCompat.Light"
        android:clickable="false"
        android:id="@+id/surface_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

我什至试着像这样加倍努力

 @Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if(event.getAction() == MotionEvent.ACTION_DOWN) {
        if(listener != null) listener.onClick(this);
    }
    return super.dispatchTouchEvent(event);
}

【问题讨论】:

  • 您的 xml 框架布局相互重叠。您的代码没有问题,请向我们展示您的 xml。
  • 我用更多细节更新了原始问题

标签: android android-custom-view android-framelayout android-touch-event


【解决方案1】:

您应该将 FrameLayout 替换为 LinearLayout 到两个不同位置的 CustomView。出现您的问题是因为 CustomView1 和 CustomView2 在 framelayout 内并且位置相同。

FrameLayout 的设计目的是在屏幕上屏蔽一个区域以显示单个项目。通常,应该使用 FrameLayout 来保存单个子视图,因为很难以一种可缩放到不同屏幕尺寸的方式组织子视图,而不会使子视图相互重叠。但是,您可以使用 android:layout_gravity 属性将多个子项添加到 FrameLayout 并通过为每个子项分配重力来控制它们在 FrameLayout 中的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多