Android: how to add view to WindowManager, and keep it floating at the top of my app all the time?

六眼飞鱼酱① 提交于 2019-12-11 02:48:49

问题


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.

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.

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.


回答1:


You have to use WindowManager for this purpose

First add permission in manifest

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

Add image which you want to appear.

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



来源:https://stackoverflow.com/questions/43626214/android-how-to-add-view-to-windowmanager-and-keep-it-floating-at-the-top-of-my

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!