Movable Floating Action Button

सबसे पहले आप अपने compileSdk और targetSdk को मिनिमम 33 कर ले।

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/floating_btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_margin="15dp"
app:srcCompat="@drawable/ic_baseline_add"
app:tint="@color/white" />
</RelativeLayout>
MainActivity.java
package in.eproduct.hindicode;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;


public class MainActivity extends AppCompatActivity implements View.OnTouchListener {

private FloatingActionButton floatingBtnAdd;
float xAxis;
float yAxis;
int lastAction;


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

floatingBtnAdd = (FloatingActionButton) findViewById(R.id.floating_btn_add);
// Add OnTouch listener to Floating action button
floatingBtnAdd.setOnTouchListener(this);


}

@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
xAxis = v.getX() - event.getRawX();
yAxis = v.getY() - event.getRawY();
lastAction = MotionEvent.ACTION_DOWN;
break;
case MotionEvent.ACTION_MOVE:
v.setX(event.getRawX() + xAxis);
v.setY(event.getRawY() + yAxis);
lastAction = MotionEvent.ACTION_MOVE;
break;
case MotionEvent.ACTION_UP:
if (lastAction == MotionEvent.ACTION_DOWN) {
// Set On Click Event
Toast.makeText(this, "Btn Clicked", Toast.LENGTH_SHORT).show();
}
break;
default:
return false;
}
return true;
}
}

Video for Movable Floating Action Button

Article By: Brajlal Prasad
Created on: 26 Sep 2023  566  Views
 Print Article
Report Error

If you want to report an error, or any suggestion please send us an email to [email protected]