How to move a button (or any widget) on touch in your Android App's layout? - can be used in games

Опубликовано: 24 Октябрь 2022
на канале: Programmer World
3,392
14

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: [email protected]

Complete source code and other details/ steps of this video are posted in the below link:
https://programmerworld.co/android/ho...


However, the main Java code is copied below also for reference:

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;
}
});
}
}



-