Android implements the function of floating buttons
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_WINDOW
Permissions, passed in Android 8.0+ (O) and aboveTYPE_APPLICATION_OVERLAY
Implement a drag-and-clickable floating button.
2. Related technical knowledge
-
Floating window permissions
Starting from Android 6.0, users need to grant "Show on other applications" permission (
ACTION_MANAGE_OVERLAY_PERMISSION
);
-
WindowManager
Used to add custom Views to the system window hierarchy,
LayoutParams
You can specify location, size, type, etc.;
-
Service
Utilize the front desk
Service
Ensure that the floating window can continue to be displayed after the background or application exits;
-
Touch event handling
On the floating view
OnTouchListener
In-processACTION_DOWN
/ACTION_MOVE
Events, drag and drop;
-
compatibility
Android O and above require use
TYPE_APPLICATION_OVERLAY
; Used belowTYPE_PHONE
orTYPE_SYSTEM_ALERT
。
Ideas for realization
-
Apply for floating window permissions
exist
MainActivity
In-depth testing()
, if not authorized, jump to the system setting request;
-
Create a foreground Service
FloatingService
InheritanceService
,existonCreate()
Initialize and toWindowManager
Add a floating button View;exist
onDestroy()
Remove the View from ;
-
Floating View Layout
floating_view.xml
Include oneImageView
(can be replaced with any View);Set the appropriate background and size;
-
Drag and click processing
Setting up the floating button
OnTouchListener
, record the coordinates and initial layout parameters when pressed, and respond to movement;exist
ACTION_UP
If the displacement is small, it is considered to be a click, triggering custom logic (such asToast
);
-
Start and Stop Service
exist
MainActivity
The "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
-
MainActivity
Check and request "Show on other applications" permission;
Click "Start" to start
FloatingService
;Click "Stop" and stop Service.
-
FloatingService
Create foreground notifications to increase process priorities;
use
WindowManager
+TYPE_APPLICATION_OVERLAY
(O and above) orTYPE_PHONE
(Below), add to the system window layerfloating_view
;exist
OnTouchListener
Medium processing drag and click: short click triggerToast
, long drag and drop updateLayoutParams
And callupdateViewLayout()
。
-
Layout and resources
floating_view.xml
Define button view;float_bg.xml
Define 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+ environmentService
andWindowManager
Implement 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
-
Beautification and animation
Add to button
ShadowLayer
orelevation
Enhance the three-dimensional sense;Add fade animation when showing/hide;
-
Custom layout
Bubble menu, multi-button floating menu, can be expanded into multiple operations;
-
Permission Boot
Customize the more friendly permission application interface, and prompt the user to open it after the check fails;
-
Resource compatibility
Optimized for dark mode, adaptive layout and other scenarios;
-
Compose Solution
Available in Jetpack Compose
AndroidView
orWindowManager
Same 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!
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 increase2023-02-02The 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-04Custom 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 it2023-03-03Android 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-03Android 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-08Example 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-08An 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-06Android'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-12EditText 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 editor2017-04-04Basic 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