'How to record and play back touch movement in android studio from onTouchListener()
I am new in android studio and app development in general. Right now I'm trying to realize a feature where an item can follow the user's finger around as if being dragged. I can do this by using onTouch to get the finger's coordinates and give them to the item, but now I need to be able to replay the motion with a click of a button. For example, if I drag the item in an S motion across the screen when I hit the play button, the item goes through the same motion again. I am not sure where to begin with implementing this, as my knowledge of the existing functions is still quite limited. Help would be greatly appreciated.
this is the code so far:
package com.example.trackballexp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private ConstraintLayout theLayout = null;
//reference to the textview
private TextView theText=null;
//to save the coordinates
private float x;
private float y;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
theLayout=(ConstraintLayout) findViewById(R.id.theLayout);
theText=(TextView) findViewById(R.id.theText);
//set the onTouchListener on the layout
theLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
//get x,y coordinate of finger
x = motionEvent.getX();
y = motionEvent.getY();
//condition: event will rapidly fire if finger is moved
if(motionEvent.getAction()==MotionEvent.ACTION_MOVE)
{
//move the text to the coordinates obtained
theText.setX(x);
theText.setY(y);
}
return true;
}
});
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
