FloatingView

repository·master·Indexed 22 days ago

https://github.com/recruit-lifestyle/floatingview

An Android library for displaying floating UI elements, such as chat heads, over other applications. It provides tools for managing window overlays, movement physics, and display cutout (notch) safety. Key components include FloatingViewManager for controlling view lifecycle and options, and the FloatingView class for handling draggable content, snapping behavior, and animation states.

Tokens
2.6K
Snippets
6
Records
13
Agent score
28%

What's inside FloatingView

  1. Handle Display Cutouts (API 28+)

    master

    To prevent the FloatingView from being obscured by display cutouts (notches), use FloatingViewManager.findCutoutSafeArea(activity) to calculate a safe area and pass it to your service.

    Note: The Activity must be in portrait orientation and windowLayoutInDisplayCutoutMode must not be set to never.

    // 1. In your Activity/Fragment, find the safe area and pass it via Intent
    final Intent intent = new Intent(activity, ChatHeadService.class);
    intent.putExtra(ChatHeadService.EXTRA_CUTOUT_SAFE_AREA, FloatingViewManager.findCutoutSafeArea(activity));
    ContextCompat.startForegroundService(activity, intent);
    
    // 2. In your Service, apply the safe area to the manager
    Rect safeArea = (Rect) intent.getParcelableExtra(EXTRA_CUTOUT_SAFE_AREA);
    mFloatingViewManager.setSafeInsetRect(safeArea);
  2. Install FloatingView via JitPack

    master

    To use FloatingView in your Android project, add the JitPack repository to your build.gradle file and then add the dependency.

    repositories {
        maven {
            url "https://jitpack.io"
        }
    }
    
    dependencies {
      implementation 'com.github.recruit-lifestyle:FloatingView:2.4.4'
    }
  3. Implement FloatingViewManager and FloatingViewListener

    master

    To display a view as a floating element, you must implement a Service and use FloatingViewManager. The FloatingViewManager constructor requires two arguments: a Context and a FloatingViewListener.

    1. Implement FloatingViewListener: Override onFinishFloatingView() to handle cleanup (e.g., calling stopSelf() on your service) when the user exits the floating view.
    2. Initialize FloatingViewManager: Create an instance within your service.
    3. Add View: Use addViewToWindow(View view, Options options) to display your layout.
    // Inside your Service
    mFloatingViewManager = new FloatingViewManager(this, new FloatingViewListener() {
        @Override
        public void onFinishFloatingView() {
            stopSelf();
        }
    });
    
    // Inflate your view
    final LayoutInflater inflater = LayoutInflater.from(this);
    final ImageView iconView = (ImageView) inflater.inflate(R.layout.widget_chathead, null, false);
    
    // Add to window
    final FloatingViewManager.Options options = new FloatingViewManager.Options();
    mFloatingViewManager.addViewToWindow(iconView, options);
  4. Configure AndroidManifest permissions and service

    master

    FloatingView requires specific permissions to display over other apps and run as a foreground service. You must also declare your implementation of the Service in the AndroidManifest.xml.

    Required Permissions:

    • android.permission.SYSTEM_ALERT_WINDOW
    • android.permission.FOREGROUND_SERVICE

    Service Declaration Example:

    <application ...>
        <service
            android:name="your.package.name.ChatHeadService"
            android:exported="false"/>
    </application>
  5. Understand the FloatingView component

    master
    The FloatingView class is a FrameLayout designed to display draggable, floating content on an Android screen. It handles complex touch interactions including dragging, long-pressing, and automatic movement to the screen edges (snapping). It manages its own window parameters to appear as an overlay, supporting features like scale animations when pressed and physics-based movement.
  6. Reference: FloatingViewManager Dynamic Methods

    master

    Dynamic methods allow you to change the behavior or appearance of the FloatingView at any time after it has been displayed.

    // Examples of dynamic updates
    mFloatingViewManager.setDisplayMode(FloatingViewManager.DISPLAY_MODE_SHOW_ALWAYS);
    mFloatingViewManager.setTrashViewEnabled(false);
    mFloatingViewManager.setFixedTrashIconImage(R.drawable.ic_trash_fixed);
  7. Reference: FloatingViewManager Dynamic Options

    master

    The following methods can be called on FloatingViewManager at any time:

    MethodDescription
    setFixedTrashIconImage(int resId)Sets the icon used when the FloatingView overlaps (does not enlarge)
    setActionTrashIconImage(int resId)Sets the icon used when the FloatingView overlaps (enlarges)
    setDisplayMode(int mode)Sets display mode: DISPLAY_MODE_SHOW_ALWAYS, DISPLAY_MODE_HIDE_ALWAYS, or DISPLAY_MODE_HIDE_FULLSCREEN
    setTrashViewEnabled(boolean enabled)If false, the trash icon is hidden during dragging (default: true)
  8. Configure Static Options for FloatingView

    master

    Static options are applied via FloatingViewManager.Options and can only be set when the view is displayed for the first time. They control the initial appearance and movement behavior.

    final FloatingViewManager.Options options = new FloatingViewManager.Options();
    options.shape = FloatingViewManager.SHAPE_CIRCLE; // or SHAPE_RECTANGLE
    options.overMargin = 16; // px
    options.moveDirection = FloatingViewManager.MOVE_DIRECTION_NEAREST;
    options.usePhysics = true;
    options.animateInitialMove = true;
    mFloatingViewManager.addViewToWindow(iconView, options);
  9. Reference: FloatingViewManager.Options (Static)

    master

    The following options are available in FloatingViewManager.Options and must be set during the initial addViewToWindow call.

    OptionDescription
    shapeFloatingViewManager.SHAPE_CIRCLE (default) or FloatingViewManager.SHAPE_RECTANGLE
    overMarginMargin over the edge of the screen in pixels (default: 0)
    floatingViewXX coordinate of initial display (default: left side)
    floatingViewYY coordinate of initial display (default: top)
    floatingViewWidthWidth of the FloatingView
    floatingViewHeightHeight of the FloatingView
    moveDirectionFloatingViewManager.MOVE_DIRECTION_DEFAULT (default), MOVE_DIRECTION_LEFT, MOVE_DIRECTION_RIGHT, MOVE_DIRECTION_NONE, MOVE_DIRECTION_NEAREST, or MOVE_DIRECTION_THROWN
    usePhysicsUse physics-based animation (default: true; requires API 16)
    animateInitialMoveIf true, animates from (X, Y) to the screen edge upon first display
  10. Configure FloatingView behavior and appearance

    master

    The FloatingView class provides several methods to customize its movement, shape, and animation behavior. Use these methods to control how the view responds to user interaction and how it appears on the screen.

    Movement and Animation

    • setMoveDirection(int moveDirection): Sets the direction the view moves to when released. Valid directions are defined in FloatingViewManager (e.g., MOVE_DIRECTION_LEFT, MOVE_DIRECTION_RIGHT, MOVE_DIRECTION_NEAREST, MOVE_DIRECTION_THROWN).
    • usePhysics(boolean usePhysics): Enables or disables physics-based animations. If true, it uses SpringAnimation or FlingAnimation (requires API 16+). If false, it reverts to standard ValueAnimator behavior. Note: This defaults to true.
    • setAnimateInitialMove(boolean animateInitialMove): Determines if the view should animate when it is first displayed.
    • setInitCoords(int x, int y): Sets the initial X and Y coordinates for the view.

    Appearance and Interaction

    • setShape(float shape): Sets the shape of the view (e.g., SHAPE_CIRCLE or SHAPE_RECTANGLE).
    • getShape(): Returns the current shape value.
    • setScale(float newScale): Scales the view by the specified factor.
    • setDraggable(boolean isDraggable): Enables or disables the ability to drag the view.
    • setOverMargin(int margin): Sets the margin that allows the view to overlap the screen edges.
    • setSafeInsetRect(Rect safeInsetRect): Sets the safe area for cutouts (notches) to ensure the view remains visible and interactable.
  11. Manage FloatingView states and lifecycle

    master

    The FloatingView transitions between different operational states which can be managed via its internal FloatingAnimationHandler (exposed through public methods).

    State Transitions

    • setNormal(): Transitions the view to a normal state, typically used when it is not interacting with other elements.
    • setIntersecting(int centerX, int centerY): Transitions the view to an intersecting state, causing it to animate towards the specified target coordinates (centerX, centerY).
    • setFinishing(): Transitions the view to a finishing state, hiding the view and preventing further movement.
    • getState(): Returns the current state of the view.

    Animation Control

    • cancelAnimation(): Immediately cancels any ongoing ValueAnimator used for edge movement.
  12. Set a touch listener on FloatingView

    master

    You can intercept touch events on the FloatingView by using setOnTouchListener. This allows you to respond to user interactions like taps or drags within the floating view's area.

    floatingView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // Handle touch events
            return false;
        }
    });