1. Basic implementation plan
1. Use WindowManager to implement global floating windows
This is the most flexible way to implement it, and you can display floating buttons on any interface:
public class FloatingButtonService extends Service { private WindowManager windowManager; private View floatingButton; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { (); // Create a floating button view floatingButton = (this).inflate(.floating_button, null); // Set button click event (.float_button).setOnClickListener(v -> { // Handle click events (this, "The floating button is clicked", Toast.LENGTH_SHORT).show(); }); // Set window parameters params = new ( .WRAP_CONTENT, .WRAP_CONTENT, .SDK_INT >= Build.VERSION_CODES.O ? .TYPE_APPLICATION_OVERLAY : .TYPE_PHONE, .FLAG_NOT_FOCUSABLE, ); // Set the initial position = | ; = 0; = 100; // Get WindowManager and add views windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); (floatingButton, params); // Add drag and drop function addDragFeature(); } private void addDragFeature() { (new () { private int initialX; private int initialY; private float initialTouchX; private float initialTouchY; @Override public boolean onTouch(View v, MotionEvent event) { switch (()) { case MotionEvent.ACTION_DOWN: initialX = ; initialY = ; initialTouchX = (); initialTouchY = (); return true; case MotionEvent.ACTION_MOVE: = initialX + (int) (() - initialTouchX); = initialY + (int) (() - initialTouchY); (floatingButton, params); return true; } return false; } }); } @Override public void onDestroy() { (); if (floatingButton != null) { (floatingButton); } } }
2. Layout file (res/layout/floating_button.xml)
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:andro android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageButton android: android:layout_width="56dp" android:layout_height="56dp" android:background="@drawable/circle_background" android:src="@drawable/ic_float_button" android:elevation="8dp" android:layout_margin="16dp" /> </FrameLayout>
3. Circular background (res/drawable/circle_background.xml)
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:andro android:shape="oval"> <solid android:color="@color/colorPrimary" /> </shape>
4. Start the service
// Start the service where the floating button needs to be displayedstartService(new Intent(context, )); // Stop servicestopService(new Intent(context, ));
2. Permission processing
1. Add permissions to
<uses-permission android:name=".SYSTEM_ALERT_WINDOW" />
2. Check and request permissions
// Check the permissions of the floating windowif (.SDK_INT >= Build.VERSION_CODES.M) { if (!(this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, ("package:" + getPackageName())); startActivityForResult(intent, OVERLAY_PERMISSION_REQ); } else { // Already have permissions, start the service startService(new Intent(this, )); } } else { // Start directly below 6.0 startService(new Intent(this, )); }
3. Advanced function expansion
1. Add animation effects
// Add animation when button clicks(v -> { // Zoom animation ObjectAnimator scaleX = (v, "scaleX", 1f, 0.8f, 1f); ObjectAnimator scaleY = (v, "scaleY", 1f, 0.8f, 1f); AnimatorSet animatorSet = new AnimatorSet(); (scaleX, scaleY); (200); (); // Perform click operation performButtonAction(); });
2. Automatic adsorption of edges
private void autoAttachToEdge() { int screenWidth = getResources().getDisplayMetrics().widthPixels; int buttonWidth = (); if ( < screenWidth / 2 - buttonWidth / 2) { // Adsorption to the left = 0; } else { // Adsorption to the right = screenWidth - buttonWidth; } (floatingButton, params); }
3. Show/hide animations
public void hideButton() { () .translationY(()) .setDuration(300) .start(); } public void showButton() { () .translationY(0) .setDuration(300) .start(); }
4. Optimization suggestions
-
Performance optimization:
- Use lightweight view levels
- Avoid frequent calls
updateViewLayout
- Using hardware acceleration
-
Memory management:
- Remove the floating window in time when it is not needed
- Automatically hide when low memory
-
User Experience:
- Add appropriate touch feedback
- Consider the position adjustment when the screen rotates
- Provides settings options for users to customize location and behavior
-
Compatibility processing:
- Handle permission differences in different Android versions
- Adapt to various screen sizes and densities
- Consider the adaptation of full screen and notch screen
V. Alternative Solutions
1. Use CoordinatorLayout + FloatingActionButton
If you only need to display the floating buttons in the app, you can use the Material Design component:
< android:layout_width="match_parent" android:layout_height="match_parent"> <!-- Other content --> < android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="16dp" android:src="@drawable/ic_add" /> </>
2. Use third-party libraries
Some popular library of floating buttons:
- FloatingView
- DraggablePanel
- FloatWindow
6. Frequently Asked Questions
-
Permissions issues:
- Make sure the request has been correct
SYSTEM_ALERT_WINDOW
Permissions - Require dynamic request permissions on Android 6.0+
- Some vendor ROMs may require additional whitelist settings
- Make sure the request has been correct
-
Incorrect location:
- examine
gravity settings
- Consider the status bar and navigation bar height
- Update position when the screen rotates
- examine
-
Click to penetrate:
- set up
FLAG_NOT_FOCUSABLE
May cause click events to penetrate - Can be passed in
onTouch
Returntrue
Come to intercept the incident
- set up
-
Memory leak:
- Make sure to remove the view when the service is destroyed
- Avoid holding Activity references in views
The above is the detailed content of the sample code for Android Studio to implement custom global floating buttons. For more information about Android Studio floating buttons, please follow my other related articles!