SoFunction
Updated on 2025-04-20

Android implements the function of floating buttons

Android implements the function of floating buttons

Updated: April 20, 2025 16:15:12 Author: Katie.
In many scenarios, we hope to see a small "floating button" (Floating Button) on any interface of the application or system, which is used to quickly start tools, display unread information or shortcut operations. Therefore, this article introduces you how to implement the floating button function in Android. Friends who need it can refer to it.

1. Project Overview

In many scenarios, we want to see a small "floating button" on any interface of the application or system, which is used to quickly start tools, display unread information or shortcut operations. Its characteristics are:

  • Always floating: Displayed on other applications and not overwritten by the current activity;

  • Can be dragged: Users can hold down and drag to any position of the screen;

  • Click to respond: Execute custom logic after clicking;

  • Automatic adaptation: Adapt to different screen sizes and screen rotation.

This project demonstrates how to use AndroidWindowManager + Service + SYSTEM_ALERT_WINDOWPermissions, passed in Android 8.0+ (O) and aboveTYPE_APPLICATION_OVERLAYImplement a drag-and-clickable floating button.

2. Related technical knowledge

  1. Floating window permissions

    • Starting from Android 6.0, users need to grant "Show on other applications" permission (ACTION_MANAGE_OVERLAY_PERMISSION);

  2. WindowManager

    • Used to add custom Views to the system window hierarchy,LayoutParamsYou can specify location, size, type, etc.;

  3. Service

    • Utilize the front deskServiceEnsure that the floating window can continue to be displayed after the background or application exits;

  4. Touch event handling

    • On the floating viewOnTouchListenerIn-processACTION_DOWN/ACTION_MOVEEvents, drag and drop;

  5. compatibility

    • Android O and above require useTYPE_APPLICATION_OVERLAY; Used belowTYPE_PHONEorTYPE_SYSTEM_ALERT

Ideas for realization

  1. Apply for floating window permissions

    • existMainActivityIn-depth testing(), if not authorized, jump to the system setting request;

  2. Create a foreground Service

    • FloatingServiceInheritanceService,existonCreate()Initialize and toWindowManagerAdd a floating button View;

    • existonDestroy()Remove the View from  ;

  3. Floating View Layout

    • floating_view.xmlInclude oneImageView(can be replaced with any View);

    • Set the appropriate background and size;

  4. Drag and click processing

    • Setting up the floating buttonOnTouchListener, record the coordinates and initial layout parameters when pressed, and respond to movement;

    • existACTION_UPIf the displacement is small, it is considered to be a click, triggering custom logic (such asToast);

  5. Start and Stop Service

    • existMainActivityThe "Start the Float" button is clicked and startedFloatingService

    • Stop Service after clicking the "Stop Floating" button.

4. Integrate code

4.1 Java code (including two classes)

package ;
 
import ;
import ;
import ;
import ;
import ;
import .*;
import ;
import ;
import ;
import ;
import ;
import .*;
import ;
import ;
import ;
import ;
import ;
import ;
 
/**
  * MainActivity: Used to request permissions and start/stop FloatingService
  */
public class MainActivity extends AppCompatActivity {
 
    private static final int REQ_OVERLAY = 1000;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        (savedInstanceState);
        setContentView(.activity_main);
 
		// Activate the floating button        findViewById(.btn_start).setOnClickListener(v -> {
            if ((this)) {
                startService(new Intent(this, ));
                finish(); // Optional: Turn off the Activity, the floating button will still be displayed            } else {
                // Request floating window permissions                Intent intent = new Intent(
                  Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                  ("package:" + getPackageName()));
                startActivityForResult(intent, REQ_OVERLAY);
            }
        });
 
		// Stop the floating button        findViewById(.btn_stop).setOnClickListener(v -> {
            stopService(new Intent(this, ));
        });
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQ_OVERLAY) {
            if ((this)) {
                startService(new Intent(this, ));
            } else {
                (this, "No floating window permission granted", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
 
/**
  * FloatingService: Front Service, add drag-and-drop floating buttons
  */
public class FloatingService extends Service {
 
    private WindowManager windowManager;
    private View floatView;
    private  params;
 
    @Override
    public void onCreate() {
        ();
        // 1. Create a front desk notification        String channelId = createNotificationChannel();
        Notification notification = new (this, channelId)
            .setContentTitle("Floating Button")
            .setContentText("The floating button is activated")
            .setSmallIcon(.ic_floating)
            .setOngoing(true)
            .build();
        startForeground(1, notification);
 
        // 2. Initialize WindowManager and LayoutParams        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        params = new ();
          = .WRAP_CONTENT;
         = .WRAP_CONTENT;
         = ;
          = .FLAG_NOT_FOCUSABLE
                      | .FLAG_LAYOUT_IN_SCREEN;
        // Support for levitation types by different SDKs        if (.SDK_INT >= Build.VERSION_CODES.O) {
             = .TYPE_APPLICATION_OVERLAY;
        } else {
             = .TYPE_PHONE;
        }
        // Default initial position         =  | ;
         = 100;
         = 300;
 
        // 3. Load custom layout        floatView = (this)
                      .inflate(.floating_view, null);
        ImageView iv = (.iv_float);
        (new FloatingOnTouchListener());
 
        // 4. Add to window        (floatView, params);
    }
 
    // Front Desk Notification Channel    private String createNotificationChannel() {
        String channelId = "floating_service";
        if (.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel chan = new NotificationChannel(
                channelId, "Hanging Button Service",
                NotificationManager.IMPORTANCE_NONE);
            ((NotificationManager)getSystemService(NOTIFICATION_SERVICE))
                .createNotificationChannel(chan);
        }
        return channelId;
    }
 
    @Override
    public void onDestroy() {
        ();
        if (floatView != null) {
            (floatView);
            floatView = null;
        }
    }
 
    @Nullable @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
 
    /**
      * Touch monitoring: Support drag and click
      */
    private class FloatingOnTouchListener implements  {
        private int initialX, initialY;
        private float initialTouchX, initialTouchY;
        private long touchStartTime;
 
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (()) {
                case MotionEvent.ACTION_DOWN:
                    // Record the data when pressed                    initialX = ;
                    initialY = ;
                    initialTouchX = ();
                    initialTouchY = ();
                    touchStartTime = ();
                    return true;
                case MotionEvent.ACTION_MOVE:
                    // Update the suspended position                     = initialX + (int)(() - initialTouchX);
                     = initialY + (int)(() - initialTouchY);
                    (floatView, params);
                    return true;
                case MotionEvent.ACTION_UP:
                    long clickDuration = () - touchStartTime;
                    // If the press and lift positions do not change much and the time is short, it will be considered a click                    if (clickDuration < 200 
                        && (() - initialTouchX,
                                      () - initialTouchY) < 10) {
                        (,
                            "The floating button is clicked!", Toast.LENGTH_SHORT).show();
                        // Activity or other operations can be started here                    }
                    return true;
            }
            return false;
        }
    }
}

4.2 XML and Manifest

<!-- ===================================================================
      — Entrance、Permissions and Service statement
=================================================================== -->
<manifest xmlns:andro
    package="">
    <!-- Floating window permissions -->
    <uses-permission android:name=".SYSTEM_ALERT_WINDOW"/>
    <application ...>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name=""/>
                <category android:name=""/>
            </intent-filter>
        </activity>
        <!-- statement Service -->
        <service android:name=".FloatingService"
                 android:exported="false"/>
    </application>
</manifest>
<!-- ===================================================================
     activity_main.xml — Includes startup/Stop button
=================================================================== -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="24dp">
 
    <Button
        android:
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start the floating button"/>
 
    <Button
        android:
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop floating button"
        android:layout_marginTop="16dp"/>
</LinearLayout>
<!-- ===================================================================
     floating_view.xml — Floating button layout
=================================================================== -->
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:andro
    android:layout_width="48dp"
    android:layout_height="48dp">
 
    <ImageView
        android:
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_float"
        android:background="@drawable/float_bg"
        android:padding="8dp"/>
</FrameLayout>
<!-- ===================================================================
     float_bg.xml — Button background(Circular + shadow)
=================================================================== -->
<shape xmlns:andro
    android:shape="oval">
    <solid android:color="#FFFFFF"/>
    <size android:width="48dp" android:height="48dp"/>
    <corners android:radius="24dp"/>
    <padding android:all="4dp"/>
    <stroke android:width="1dp" android:color="#CCCCCC"/>
    <!-- shadow需在代码中或 ShadowLayer Settings in -->
</shape>

5. Code interpretation

  1. MainActivity

    • Check and request "Show on other applications" permission;

    • Click "Start" to startFloatingService;Click "Stop" and stop Service.

  2. FloatingService

    • Create foreground notifications to increase process priorities;

    • useWindowManager + TYPE_APPLICATION_OVERLAY(O and above) orTYPE_PHONE(Below), add to the system window layerfloating_view

    • existOnTouchListenerMedium processing drag and click: short click triggerToast, long drag and drop updateLayoutParamsAnd callupdateViewLayout()

  3. Layout and resources

    • floating_view.xmlDefine button view;

    • float_bg.xmlDefine a circular background;

    • Declare the necessary permissions and Service.

6. Project Summary

This article introduces how to pass the front desk in Android 8.0+ environmentServiceandWindowManagerImplement aButtons that can be dragged, clicked, and always floated over other applications. Core advantages:

  • System floating window: No activity is dependent on, it can be displayed on any interface;

  • Flexible drag: The user can freely drag to any position of the screen;

  • Click to callback: Custom logic can be executed when clicked (start Activity, switch pages, etc.);

  • Front Desk Service: Ensure that it can be displayed continuously in the background and is not easily recycled by the system.

7. Practical suggestions and future prospects

  1. Beautification and animation

    • Add to buttonShadowLayerorelevationEnhance the three-dimensional sense;

    • Add fade animation when showing/hide;

  2. Custom layout

    • Bubble menu, multi-button floating menu, can be expanded into multiple operations;

  3. Permission Boot

    • Customize the more friendly permission application interface, and prompt the user to open it after the check fails;

  4. Resource compatibility

    • Optimized for dark mode, adaptive layout and other scenarios;

  5. Compose Solution

    • Available in Jetpack ComposeAndroidVieworWindowManagerSame implementation, combined withHandle drag and drop.

The above is the detailed content of Android's implementation of the floating button function. For more information about Android's floating button, please follow my other related articles!

  • Android
  • Suspension
  • Button

Related Articles

  • Flutter Android multi-window solution implementation

    This article mainly introduces a detailed explanation of the practical examples of the implementation of Flutter Android multi-window solution. Friends in need can refer to it for reference. I hope it can be helpful. I wish you more progress and an early promotion and salary increase
    2023-02-02
  • The implementation steps for entering a payment password for Android wallet payment

    This article mainly introduces the entry of payment password for Android wallet payment. Friends who need it can refer to it.
    2018-04-04
  • Custom editText underline in Android development

    This article mainly introduces relevant information about custom editText underscores in Android development. Friends who need it can refer to it
    2023-03-03
  • Android Bezier curve achieves live broadcast like effect

    This article mainly introduces the Android Bezier curve to achieve live broadcast like effect. The sample code in the article is introduced in detail and has a certain reference value. Interested friends can refer to it.
    2018-03-03
  • Android realizes automatic filling of SMS verification code

    This article mainly introduces the implementation process of the Android SMS verification code automatic filling function. Interested friends can refer to it.
    2016-08-08
  • Example of Android development method of creating dialog boxes based on DialogFragment

    This article mainly introduces the method of creating dialog boxes based on DialogFragment in Android development. It analyzes the specific functions and layout-related implementation techniques of DialogFragment creation dialog boxes based on examples. Friends who need it can refer to it.
    2017-08-08
  • An example of Android using direction sensors to obtain a mobile phone's relative angle

    The following is an example to introduce to you the relative angle of Android using direction sensors to obtain mobile phones. Those who don’t know can refer to it.
    2013-06-06
  • Android's demo instance of the control moving with your finger

    Hello everyone, this article mainly talks about the demo examples of Android's controls that follow the fingers. Interested students, come and take a look. If it is helpful to you, remember to bookmark it for the convenience of browsing next time.
    2021-12-12
  • EditText limits the number of digits before and after decimal places

    Below, the editor will bring you an example of EditText limiting the number of digits before and after the decimal point. The editor thinks it is quite good, so I will share it with you now and give you a reference. Let's take a look with the editor
    2017-04-04
  • Basic use of the Android Jetpack component Navigation navigation component

    This article mainly introduces what Navigation is and what is the process of using it, and has been operated in combination with actual cases. Navigation has many other uses, such as conditional navigation, nested diagrams, excessive animation and other functions. If you have the opportunity, please refer to it.
    2022-06-06

Latest Comments