I want to write a penalty shootout application, now I have set up the background and added the ball and the goalkeeper to the map. How do I make it so that when I tap on the screen, the ball follows my touch on the screen. How to do this? How to track the touch on the screen and enter the ball after my touch.
MainActivity.kt
JavaScript
x
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
window.decorView.systemUiVisibility =
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
View.SYSTEM_UI_FLAG_FULLSCREEN
}
activity_main.xml
JavaScript
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/main_bg"
tools:context=".MainActivity">
<ImageView
android:id="@+id/ball"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ball"
app:layout_editor_absoluteX="150dp"
app:layout_editor_absoluteY="500dp"
tools:ignore="MissingConstraints" />
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
app:layout_editor_absoluteX="125dp"
app:layout_editor_absoluteY="300dp"
android:src="@drawable/goalkeeper"
</androidx.constraintlayout.widget.ConstraintLayout>
Advertisement
Answer
I found the answer to my question, you need to use onTouchListener. My code looks like this:
JavaScript
ImageView ballView;
float xDown = 0, yDown = 0;
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
ballView = findViewById(R.id.ball);
ballView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getActionMasked()) {
///пользователь просто прикоснулся к мячу
case MotionEvent.ACTION_DOWN:
xDown = motionEvent.getX();
yDown = motionEvent.getY();
break;
///пользователь водит по экрану
case MotionEvent.ACTION_MOVE:
float movedX, movedY;
movedX = motionEvent.getX();
movedY = motionEvent.getY();
float distanceX = movedX - xDown;
float distanceY = movedY - yDown;
ballView.setX(ballView.getX() + distanceX);
ballView.setY(ballView.getY() + distanceY);
break;
}
return true;
}
});