Android应用内悬浮窗Activity的简单实现

 更新时间:2022年01月05日 11:44:42   作者:rustfisher.com  
悬浮窗相信大家应该都不陌生,下面这篇文章主要给大家介绍了关于Android应用内悬浮窗Activity简单实现的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下

前言

悬浮窗是一种比较常见的需求。例如把视频通话界面缩小成一个悬浮窗,然后用户可以在其他界面上处理事情。

本文给出一个简单的应用内悬浮窗实现。可缩小activity和还原大小。可悬浮在同一个app的其他activity上。使用TouchListener监听触摸事件,拖动悬浮窗。

缩放方法

缩放activity需要使用WindowManager.LayoutParams,控制window的宽高

在activity中调用

android.view.WindowManager.LayoutParams p = getWindow().getAttributes();
p.height = 480; // 高度
p.width = 360;  // 宽度
p.dimAmount = 0.0f; // 不让下面的界面变暗
getWindow().setAttributes(p);

dim: adj. 暗淡的; 昏暗的; 微弱的; 不明亮的; 光线暗淡的; v. (使)变暗淡,变微弱,变昏暗; (使)减弱,变淡漠,失去光泽;

修改了WindowManager.LayoutParams的宽高,activity的window大小会发生变化。

要变回默认大小,在activity中调用

getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

如果缩小时改变了位置,需要把window的位置置为0

WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.x = 0;
lp.y = 0;
getWindow().setAttributes(lp);

activity变小时,后面可能是黑色的背景。这需要进行下面的操作。

悬浮样式

在styles.xml里新建一个MeTranslucentAct。

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="TranslucentAct" parent="AppTheme">
        <item name="android:windowBackground">#80000000</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowAnimationStyle">@android:style/Animation.Translucent</item>
    </style>
</resources>

主要style是AppCompat的。

指定一个window的背景android:windowBackground 使用的Activity继承自androidx.appcompat.app.AppCompatActivity

activity缩小后,背景是透明的,可以看到后面的其他页面

点击穿透空白

activity缩小后,点击旁边空白处,其他组件能接到点击事件

onCreate方法的setContentView之前,给WindowManager.LayoutParams添加标记FLAG_LAYOUT_NO_LIMITSFLAG_NOT_TOUCH_MODAL

WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.flags = WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;

mBinding = DataBindingUtil.setContentView(this, R.layout.act_float_scale);

移动悬浮窗

监听触摸事件,计算出手指移动的距离,然后移动悬浮窗。

private boolean mIsSmall = false; // 当前是否小窗口
private float mLastTx = 0; // 手指的上一个位置x
private float mLastTy = 0;
// ....

    mBinding.root.setOnTouchListener((v, event) -> {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.d(TAG, "down " + event);
                mLastTx = event.getRawX();
                mLastTy = event.getRawY();
                return true;
            case MotionEvent.ACTION_MOVE:
                Log.d(TAG, "move " + event);
                float dx = event.getRawX() - mLastTx;
                float dy = event.getRawY() - mLastTy;
                mLastTx = event.getRawX();
                mLastTy = event.getRawY();
                Log.d(TAG, "  dx: " + dx + ", dy: " + dy);
                if (mIsSmall) {
                    WindowManager.LayoutParams lp = getWindow().getAttributes();
                    lp.x += dx;
                    lp.y += dy;
                    getWindow().setAttributes(lp);
                }

                break;
            case MotionEvent.ACTION_UP:
                Log.d(TAG, "up " + event);
                return true;
            case MotionEvent.ACTION_CANCEL:
                Log.d(TAG, "cancel " + event);
                return true;
        }
        return false;
    });

mIsSmall用来记录当前activity是否变小(悬浮)。

在触摸监听器中返回true,表示消费这个触摸事件。

event.getX()event.getY()获取到的是当前View的触摸坐标。 event.getRawX()event.getRawY()获取到的是屏幕的触摸坐标。即触摸点在屏幕上的位置。

例子的完整代码

启用了databinding

android {
    dataBinding {
        enabled = true
    }
}

styles.xml

新建一个样式

    <style name="TranslucentAct" parent="AppTheme">
        <item name="android:windowBackground">#80000000</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowAnimationStyle">@android:style/Animation.Translucent</item>
    </style>

layout

act_float_scale.xml里面放一些按钮,控制放大和缩小。 ConstraintLayout拿来监听触摸事件。

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#555555">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical"
            app:layout_constraintTop_toTopOf="parent">

            <Button
                android:id="@+id/to_small"
                style="@style/NormalBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="变小" />

            <Button
                android:id="@+id/to_reset"
                style="@style/NormalBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="12dp"
                android:text="还原" />
        </LinearLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

activity

FloatingScaleAct

import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.WindowManager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.rustfisher.tutorial2020.R;
import com.rustfisher.tutorial2020.databinding.ActFloatScaleBinding;

public class FloatingScaleAct extends AppCompatActivity {
    private static final String TAG = "rfDevFloatingAct";

    ActFloatScaleBinding mBinding;

    private boolean mIsSmall = false; // 当前是否小窗口
    private float mLastTx = 0; // 手指的上一个位置
    private float mLastTy = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.flags = WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;

        mBinding = DataBindingUtil.setContentView(this, R.layout.act_float_scale);

        mBinding.toSmall.setOnClickListener(v -> toSmall());
        mBinding.toReset.setOnClickListener(v -> {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.x = 0;
            lp.y = 0;
            getWindow().setAttributes(lp);
            getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            mIsSmall = false;
        });

        mBinding.root.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    Log.d(TAG, "down " + event);
                    mLastTx = event.getRawX();
                    mLastTy = event.getRawY();
                    return true;
                case MotionEvent.ACTION_MOVE:
                    Log.d(TAG, "move " + event);
                    float dx = event.getRawX() - mLastTx;
                    float dy = event.getRawY() - mLastTy;
                    mLastTx = event.getRawX();
                    mLastTy = event.getRawY();
                    Log.d(TAG, "  dx: " + dx + ", dy: " + dy);
                    if (mIsSmall) {
                        WindowManager.LayoutParams lp = getWindow().getAttributes();
                        lp.x += dx;
                        lp.y += dy;
                        getWindow().setAttributes(lp);
                    }

                    break;
                case MotionEvent.ACTION_UP:
                    Log.d(TAG, "up " + event);
                    return true;
                case MotionEvent.ACTION_CANCEL:
                    Log.d(TAG, "cancel " + event);
                    return true;
            }
            return false;
        });
    }

    private void toSmall() {
        mIsSmall = true;

        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();
        WindowManager.LayoutParams p = getWindow().getAttributes();
        p.height = (int) (d.getHeight() * 0.35);
        p.width = (int) (d.getWidth() * 0.4);
        p.dimAmount = 0.0f;
        getWindow().setAttributes(p);
    }
}

manifest里注册这个activity

<activity
    android:name=".act.FloatingScaleAct"
    android:theme="@style/TranslucentAct" />

运行效果

在红米9A(Android 10,MIUI 12.5.1 稳定版)和荣耀(Android 5.1)上运行OK

悬浮窗效果-红米9A

小结

为实现悬浮窗效果,思路是改变activity大小,将activity所在window的背景设置透明,监听触摸事件改变window的位置。 主要使用的类 WindowManager.LayoutParams

到此这篇关于Android应用内悬浮窗Activity实现的文章就介绍到这了,更多相关Android悬浮窗Activity内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Android开发笔记 今天学到的一些属性

    Android开发笔记 今天学到的一些属性

    离开实验室之前再贴上今天下午自己学到的一些基础知识 上午干嘛了呢,忙着数据恢复呢
    2012-11-11
  • Android实现录音功能实现实例(MediaRecorder)

    Android实现录音功能实现实例(MediaRecorder)

    本篇文章主要介绍了Android实现录音的实例代码(MediaRecorder),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-07-07
  • Android实现跳动的小球加载动画效果

    Android实现跳动的小球加载动画效果

    Android中有各式各样的加载动画,大家多多少少都见过,比如用过美团客户端的用户对美团那个加载小人的动画印象很深刻,一个可爱的小人在那拼命的跑。这样的动画实现其实还有很多,今天这里就来实现一个跳动的小球效果。有需要的可以参考借鉴。
    2016-08-08
  • Android下拉刷新上拉加载更多左滑动删除

    Android下拉刷新上拉加载更多左滑动删除

    本文给大家分享一段代码实现Android下拉刷新上拉加载更多仿ios左滑动删除item,非常实用,代码简单易懂,特此分享脚本之家平台供大家学习
    2016-01-01
  • 详解Android6.0运行时权限管理

    详解Android6.0运行时权限管理

    自从Android6.0发布以来,在权限上做出了很大的变动,不再是之前的只要在manifest设置就可以任意获取权限,而是更加的注重用户的隐私和体验。本文详细介绍了Android6.0运行时权限管理。需要的朋友一起来看下吧
    2016-12-12
  • Android studio无法创建类和接口和提示问题的完美解决办法

    Android studio无法创建类和接口和提示问题的完美解决办法

    这篇文章主要介绍了Android studio无法创建类和接口和提示问题解决办法,内容比较简单,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2018-04-04
  • android底部菜单栏实现原理与代码

    android底部菜单栏实现原理与代码

    底部菜单栏很重要,我看了一下很多应用软件都是用了底部菜单栏做,我这里使用了tabhost做了一种通用的(就是可以像微信那样显示未读消息数量的,虽然之前也做过但是layout下的xml写的太臃肿,这里去掉了很多不必要的层,个人看起来还是不错的,所以贴出来方便以后使用
    2013-01-01
  • android开发通过Scroller实现过渡滑动效果操作示例

    android开发通过Scroller实现过渡滑动效果操作示例

    这篇文章主要介绍了android开发通过Scroller实现过渡滑动效果,结合实例形式分析了Android Scroller类实现过渡滑动效果的基本原理与实现技巧,需要的朋友可以参考下
    2020-01-01
  • Android中butterknife的使用与自动化查找组件插件详解

    Android中butterknife的使用与自动化查找组件插件详解

    这篇文章主要给大家介绍了关于Android中butterknife的使用与自动化查找组件插件的相关资料,文中通过示例代码介绍的非常详细,对各位Android开发者们具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-10-10
  • Android AsyncTask用法巧用实例代码

    Android AsyncTask用法巧用实例代码

    这篇文章主要介绍了Android AsyncTask用法巧用实例代码的相关资料,需要的朋友可以参考下
    2017-01-01

最新评论