In this video it shows how to implement or develop your Android App in which the buttons or any other widget moves on touching it.
It uses onTouchListener on the widget to move it and then sets it position using setTop, setBottom, setLeft and setRight APIs.
This concept can be used while designing some simple game in your Android App layout.
I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com
Complete source code and other details:
package com.programmerworld.movingbuttonapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button buttonMove;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonMove = findViewById(R.id.MovingButton);
buttonMove.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (buttonMove.getTop() != 200){
buttonMove.setTop(200);
buttonMove.setBottom(340);
buttonMove.setLeft(100);
buttonMove.setRight(360);
}
else{
buttonMove.setTop(400);
buttonMove.setBottom(540);
buttonMove.setLeft(300);
buttonMove.setRight(560);
}
return false;
}
});
}
}
<?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"
tools:context=".MainActivity">
<Button
android:id="@+id/MovingButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="152dp"
android:layout_marginTop="304dp"
android:text="Moving Button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>