Search code examples
javaandroidimagetouch-eventontouch

How can I move an image based on a user's touch?


I am trying to get an image to move, either to the Left Or Right, when the user touches either the Left Or Right of their device's screen. I have the following code....I have run the Emulator, in Android Studio, and when I click on the Right or Left sides of the Emulator's Screen....nothing happens. What is wrong with this code? All answers are welcome! I have entered the following code in the Activity that has the image I want to move:

public class GameScreen1 extends AppCompatActivity implements View.OnTouchListener{


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game_screen1);


    ImageView circle1 = (ImageView) findViewById(R.id.circle1);

}

@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (v.getId()) {
        case R.id.circle1:
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                //WHAT CODE SHOULD I PUT INSTEAD OF THE FLOAT X AND X++
                int ScreenWidth = getResources().getDisplayMetrics().widthPixels;
                float Xtouch = event.getRawX();
                int sign = Xtouch > 0.5*ScreenWidth ? 1 : -1;
                float XToMove = 50;
                int durationMs = 50;
                v.animate().translationXBy(sign*XToMove).setDuration(durationMs);
            }
            break;
    }
    return false;
}

}


Solution

  • Add ID to your root layout in the activity and add TouchListener on it.

    Here's an example:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:id="@+id/cl_root"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
    
    </android.support.constraint.ConstraintLayout>
    

    And This is the code of your activity:

    public class MainActivity extends AppCompatActivity {
    
        ConstraintLayout layout;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            layout = findViewById(R.id.cl_root);
            layout.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    int screenWidth = getResources().getDisplayMetrics().widthPixels;
                    int x = (int)event.getX();
                    if ( x >= ( screenWidth/2) ) {
                        //Right touch
                    }else {
                        //Left touch
                    }
                    return false;
                }
            });
    
        }
    }