Android:如何将视图添加到 WindowManager,并使其始终悬浮在我的应用程序顶部? [英] Android: how to add view to WindowManager, and keep it floating at the top of my app all the time?

查看:31
本文介绍了Android:如何将视图添加到 WindowManager,并使其始终悬浮在我的应用程序顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个视图显示在我的应用程序顶部,当它显示时,它可以继续显示在我所有应用程序的其他视图(所有片段和活动)的顶部.这听起来像一个浮动操作按钮,但会始终显示在我的应用程序顶部.

I need a view to show up at the top of my application, and when it's shown, it can keep showing at the top of all my application's other view(all the fragment and activity). It sounds like a Floating Action Button, but will always show at the top of my app.

我知道我可以通过向手机的 WindowManager 添加视图来实现,并在退出应用程序时隐藏它,在恢复应用程序时再次显示它.这个棘手的方法可以工作,但它也需要一些额外的许可,这是我试图避免的.

I know I can do it via adding view to my phone's WindowManager, and hide it when I quit my app, show it again when I resume my app. This tricky method can work, but it also require some additional permission, which is I am trying to avoid.

如果我只想在我的应用中显示,是否可以在不征得用户额外许可的情况下实现?如果答案是肯定的,那么如何呢?关键似乎是视图的一些 LayoutParams,我尝试过但失败了.

If I only want to show in my app, can I achieve it without asking additional permission from user? If the answer is yes, then how? The key seems like some LayoutParams for the view, I tried but failed.

如果答案能显示一些详细的代码和解释就好了.

Would be nice if answer can show some detail code and explanation.

推荐答案

为此你必须使用 WindowManager

You have to use WindowManager for this purpose

首先在清单中添加权限

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

添加要显示的图像.

chatheadImg = (ImageView)chatheadView.findViewById(R.id.chathead_img);

然后创建服务并向其添加窗口管理器.

Then make the service and add window manager to it.

WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            PixelFormat.TRANSLUCENT);
    params.gravity = Gravity.TOP | Gravity.LEFT;
    params.x = 0;
    params.y = 100;

只需在视图上注册触摸事件

And just register touch events on view

chatheadView.setOnTouchListener(new View.OnTouchListener() {
@Override
        public boolean onTouch(View v, MotionEvent event) {
        Switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:

                      //To do
                    break;
                case MotionEvent.ACTION_MOVE:

                break;

});

查看这些教程以更好地理解

check these tutorials for better understanding

http://www.androidhive.info/2016/11/android-floating-widget-like-facebook-chat-head/

https://github.com/henrychuangtw/Android-ChatHead

这篇关于Android:如何将视图添加到 WindowManager,并使其始终悬浮在我的应用程序顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆