Search code examples
androidimageviewgesture

How to implement custom gesture on an ImageView?


I succeed in implementing a custom gesture at the level of the activity, through the following "standard" code. So the entire screen "reacts" to the gesture.

However I would like to be able to detect my custom gesture when it is done on a specific ImageView. Is it possible?

Thanks

public class DisplayMultiImageActivity extends Activity implements OnGesturePerformedListener {

    GestureLibrary mLibrary;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_multiimage);

        mLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures);
        if (!mLibrary.load()) {
            finish();
        }

        GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
        gestures.addOnGesturePerformedListener(this);

    }

    @Override
    public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
        ArrayList<Prediction> predictions = mLibrary.recognize(gesture);
        if (predictions.size() > 0 && predictions.get(0).score > 1.0) {
            String result = predictions.get(0).name;

            if ("mycustomgesture".equalsIgnoreCase(result)) {
                Toast.makeText(this, "Custom gesture detected!!", Toast.LENGTH_LONG).show();
            }
        }
    }

}

Solution

  • In your XML-file, the GestureOverlayView probably takes up the whole screen. If you want it to only react on gestures on an ImageView, you should set the GestureOverlayView over the ImageView.

    <android.gesture.GestureOverlayView
            android:id="@+id/gestures"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
    
            <ImageView
                 // attributes of ImageView />
    
    </android.gesture.GestureOverlayView>
    

    EDIT

    The onGesturePerformedListener receives the GestureOverlayView on which the gesture was performed in the method onGesturePerformed(GestureOverlayView, Gesture).

    In this method, check which GestureOverlayView was used, and execute the related action.

    So you should set a diferent GestureOverlayView on every ImageView you want to track Gestures on.

        @Override
        public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
               switch(overlay.getId()) {
               case (R.id.overlay1):
                    \\ DO SOMETHING WITH IMAGEVIEW 1
                    break;
               case (R.id.overlay2):
                    \\ DO SOMETHING WITH IMAGEVIEW 2
                    break;
               case (R.id.overlay3):
                    \\ DO SOMETHING WITH IMAGEVIEW 3
                    break;
               default:
                    \\
               }
         }