2

I am adding Custom Views to a FrameLayout programmatically:

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);

Now, when I tap my custom view the event is getting triggered for both custom views and not only for the one I tapped. I can see both Toasts one after the other. Any ideas why ?

UPDATE 1 - More Details I am working on a AR App and I try to integrate the Views based on the location data (GPS) which is working just fine. The only thing that does not work is the listener for my custom view. I can see my two custom views inside the CameraView/SurfaceView and they are not on the same position

    <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>

I even tried to go the extra mile like this

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

1 Answers1

1

You should replace FrameLayout to LinearLayout to two CustomView don't have same position. Your issue occurred because CustomView1 and CustomView2 inside a framelayout and have position same.

FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.

Tung Tran
  • 2,885
  • 2
  • 17
  • 24