How to Use windowmanager and windowmanager. layoutparams and implement floating window

Source: Internet
Author: User



When writing Android programs, windowmanager is generally used to obtain the width and height of the screen to layout small things. Basically, there is no other interface.

These two days I want to write a simple toast-like things, custom layout, and suddenly found that the original toast time cannot be defined by myself, there are only two fixed time, they are 2 S and 3.5 s respectively. My need is to customize the display time, which obviously cannot meet my needs. But how does one display a view above all existing views?

The Android platform is composed of one activity and one or more views. Therefore, when we want to display an interface, we first think of creating an activity and implementing all the operations in the activity, or a dialog or toast. This method is simple, but in some cases, we only need simple display. Using activity is obviously redundant. What should we do at this time?

Originally, the window mechanism of the entire android system was based on a windowmanager interface. This interface can be used to add a View to the screen or delete a view from the screen. It targets the screen at one end of the object and view at the other end, directly ignoring our previous activity or dialog stuff. In fact, the underlying implementation of our activity or diolog is also implemented through windowmanager, which is global and the entire system is the only thing. It is the bottom layer of the display view.

The windowmanager method is very simple. Basically, three addviews, removeview, and updateviewlayout are used.

Windowmanager. layoutparams has many attributes, which are very rich. For more information, see the SDK documentation.


Write a simple code:

12345 WindowManager mWm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);  
Button view =
new Button(this);  
view.setText("window manager test!");  
WindowManager.LayoutParams mParams =
new WindowManager.LayoutParams();   
mWm.addView(view, mParams);


The display of our button is basically irrelevant to the current running environment. What activity or desktop is the current? using this underlying result brings great flexibility to your programming, however, it should be noted that it should be destroyed, which is required. The destruction is actually a remove.

However, there will be a problem with this writing, that is, the view is displayed on the top, but the view behind it cannot get the focus. When the coordinates of your touch are beyond the range of the last view

12 mParams = new
WindowManager.LayoutParams();   mWm.updateViewLayout(view, mParams);


When the following view is required to get the focus:

12 mParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;   
mWm.updateViewLayout(view, mParams);




The following is a complete sample code:

123456789101112131415161718192021222324252627 public class myFloatView extends Activity {  
    /** Called when the activity is first created. */    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        Button bb=new
Button(getApplicationContext());           WindowManager wm=(WindowManager)getApplicationContext().getSystemService("window");  
        WindowManager.LayoutParams wmParams =
new WindowManager.LayoutParams();  
         * The following are related properties of windowmanager. layoutparams:
         * For more information, see the SDK documentation.
         */        wmParams.type=2002;  
// This is the key. You can try 2003        wmParams.format=1;  
         * The flags here is also critical.
         * The actual code is wmparams. Flags | = flag_not_focusable;
         * 40 is the default property of wmparams (32) + flag_not_focusable (8)
         */        wmParams.flags=40;  
        wm.addView(bb, wmParams); 
// Create a view    }  


Do not forget to add permissions in androidmanifest. xml:

1 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"


PS: here is an example of the meaning of the type value:

12345678910111213 /**         * Window type: phone.  These are non-application windows providing
        * user interaction with the phone (in particular incoming calls).
        * These windows are normally placed above all applications, but behind
        * the status bar.
        */       public static final int TYPE_PHONE              = FIRST_SYSTEM_WINDOW+2;
        * Window type: system window, such as low power alert. These windows
        * are always on top of application windows.
        */public static final int TYPE_SYSTEM_ALERT       = FIRST_SYSTEM_WINDOW+3;


The value of first_system_window is 2000. The difference between 2003 and 2002 is that 2003 views are higher than 2002 Views and can be displayed on the system drop-down status bar!

The windowmanager method is very simple. Basically, three addviews, removeview, and updateviewlayout are used.

Windowmanager. layoutparams has many attributes, which are very rich. For more information, see the SDK documentation.


The windowmanager. layoutparams class is used in the above Code. Now we can summarize its usage as follows: windowmanager. layoutparams is a nested class of the windowmanager interface and inherits from viewgroup. layoutparams.
Its content is rich. In fact, the main content of windowmanager. Java is defined by this class. Next we will analyze this class:
Public static class windowmanager. layoutparams extends viewgroup. layoutparams implements parcelable

Inheritance relationship
Java. Lang. Object
Using Android. View. viewgroup. layoutparams
Using Android. View. windowmanager. layoutparams

Inherited attributes and constants
Attributes inherited from ViewManager. layoutparams:
Android: layout_height
Specifies the Basic height of the view.

Android: layout_width
Specifies the basic width of the view.

Constants inherited from ViewManager. layoutparams:
Two variables:

Attribute and available constant Definitions
1. Public int X;
If the gravity attribute is ignored, it indicates the absolute X position of the window.
What is the gravity attribute? Simply put, it is how the window is docked.
After gravity. Left or gravity. Right is set, the X value indicates the distance to a specific edge.
2. Public int y;
If the gravity attribute is ignored, it indicates the absolute y position of the window.
After gravity. Top or gravity. Bottom is set, the Y value indicates the distance to a specific edge.
3. Public float horizontalweight;
Public float verticalweight;
In the vertical or horizontal direction, how much extra space (pixels) is reserved for the associated view ). If it is 0, the view cannot be stretched.
In other cases, the Extended Space (pixels) is evenly distributed by widgets.
4. Public int type;
Window Type.
There are three main types:
The value is between first_application_window and last_application_window.
Is a common, top-layer application window. You must set the token of the activity.
The value is between first_sub_window and last_sub_window.
Associated with the top-level window, the token must be set as the token of the host window to which it is attached.
The value is between first_system_window and last_system_window.
Used for specific system functions. It cannot be used in applications and requires special permissions.

The value of type is defined below:
Application Window.
Public static final int first_application_window = 1;

The "base" Window of all program windows, and other application windows are displayed on it.
Public static final int type_base_application = 1;

Common application function program window. The token must be set as the activity token to indicate who the window belongs.
Public static final int type_application = 2;

The window displayed when the application starts. The application itself does not use this type.
It is used for the system to display some information until the application can open its own window.
Public static final int type_application_starting = 3;

The application window ends.
Public static final int last_application_window = 99;

Subwindow. The Z-order and coordinate spaces of subwindows depend on their host windows.
Public static final int first_sub_window = 1000;

The panel window is displayed on the upper layer of the host window.
Public static final int type_application_panel = first_sub_window;

Media window, such as video. Displayed at the lower layer of the host window.
Public static final int type_application_media = first_sub_window + 1;

The Child Panel of the application window. Displayed on the upper layer of all panel windows. (The more "sub", the closer the GUI is)
Public static final int type_application_sub_panel = first_sub_window + 2;

Dialog box. Similar to a panel window, draw a window similar to a top-level window, rather than a child window of the host.
Public static final int type_application_attached_dialog = first_sub_window + 3;

Media information. The display must be transparent (translucent) between the media layer and the program window. (For example, show subtitles)
Public static final int type_application_media_overlay = first_sub_window + 4;

The child window ends. (End of types of sub-Windows)
Public static final int last_sub_window = 1999;

System window. Non-application creation.
Public static final int first_system_window = 2000;

Status Bar. There can be only one status bar; it is located at the top of the screen, and other windows are located below it.
Public static final int type_status_bar = first_system_window;

Search bar. There can be only one search bar; it is located above the screen.
Public static final int type_search_bar = first_system_window + 1;

Phone window. It is used for telephone interaction (especially incoming calls ). It is placed above all applications and under the status bar.
Public static final int type_phone = first_system_window + 2;

System prompt. It always appears in the application window.
Public static final int type_system_alert = first_system_window + 3;

Screen lock window.
Public static final int type_keyguard = first_system_window + 4;

Information Window. Display toast.
Public static final int type_toast = first_system_window + 5;

System top-level window. It is displayed on top of everything else. This window cannot obtain the input focus; otherwise, the screen lock will be affected.
Public static final int type_system_overlay = first_system_window + 6;

The phone number is preferred. It is displayed when the screen is locked. This window cannot obtain the input focus; otherwise, the screen lock will be affected.
Public static final int type_priority_phone = first_system_window + 7;

System dialog box. (For example, the volume adjustment box ).
Public static final int type_system_dialog = first_system_window + 8;

The dialog box displayed when the screen is locked.
Public static final int type_keyguard_dialog = first_system_window + 9;

The system internal error message is displayed on top of all content.
Public static final int type_system_error = first_system_window + 10;

The internal input method window is displayed on the normal UI. Applications can be laid out again to avoid being overwritten by this window.
Public static final int type_input_method = first_system_window + 11;

The internal input method dialog box is displayed on top of the current input method window.
Public static final int type_input_method_dialog = first_system_window + 12;

Wallpaper window.
Public static final int type_wallpaper = first_system_window + 13;

Slide Panel of the status bar.
Public static final int type_status_bar_panel = first_system_window + 14;

The system window ends.
Public static final int last_system_window = 2999;

5. Public int memorytype;
Specifies the memory buffer type used by the window. The default value is normal.

The value of memorytype is defined below:
The window buffer is in the primary memory.
Public static final int memory_type_normal = 0;

The window buffer is located in the memory area that can be accessed by DMA or hardware acceleration.
Public static final int memory_type_hardware = 1;

The window buffer is located in the area that can be accessed by the graphic accelerator.
Public static final int memory_type_gpu = 2;

The window buffer does not have its own buffer and cannot be locked. The buffer is provided by the local method.
Public static final int memory_type_push_buffers = 3;

6. Public int flags;
Behavior option/flag. The default value is none.
The value of flags is defined below:
The content after the window is dimmed.
Public static final int flag_dim_behind = 0x00000002;

The content after the window is blurred.
Public static final int flag_blur_behind = 0x00000004;

Do not get focus.
You cannot obtain the key input focus, so you cannot send a key or button event to it. The time that will be sent to the window after which the focus can be obtained. This option also sets the flag_not_touch_modal option. Setting this option means that the window cannot interact with the soft input method, so its Z-order is independent of any active input method (in other words, it can be displayed in full screen, if needed, can overwrite the input method window ). To modify this line, see the flag_alt_focusalbe_im option.
Public static final int flag_not_focusable = 0x00000008;

Do not accept touch screen events.
Public static final int flag_not_touchable = 0x00000010;

When the window can get the focus (the flag_not_focusalbe option is not set), the point device event (mouse, touch screen) outside the window is still sent to the subsequent window for processing. Otherwise, it excludes all vertex device events, regardless of whether they occur within the window.
Public static final int flag_not_touch_modal = 0x00000020;

If this flag is set, when the device sleep, click the touch screen and the device will receive this first touch event.
Usually, the first touch event is consumed by the system, and the user will not see the response of their clicking on the screen.
Public static final int flag_touchable_when_waking = 0x00000040;

When this window is visible to the user, keep the device open and keep the brightness unchanged.
Public static final int flag_keep_screen_on = 0x00000080;

The window occupies the entire screen, ignoring the surrounding decorative border (such as the status bar ). This window should take into account the content of the decorative border.
Public static final int flag_layout_in_screen = 0x00000100;

The window can be extended out of the screen.
Public static final int flag_layout_no_limits = 0x00000200;

Hide all screen decorations (such as status bars) when the window is displayed ). Make the window occupy the entire display area.
Public static final int flag_fullscreen = 0x00000400;

This option overwrites the flag_fullscreen option and forces the screen Decoration (such as status bar) to pop up.
Public static final int flag_force_not_fullscreen = 0x00000800;

Jitter. Display Method of translucent. It is also called "Point-through ". Devices with poor image processing often use dot-passthrough instead of Alpha mixing.
Public static final int flag_dither = 0x00001000;

Screen is not allowed.
Public static final int flag_secure = 0x00002000;

The layout parameter is used to indicate the display ratio.
Public static final int flag_scaled = 0x00004000;

This option prevents cheek misoperation on the screen when the screen may have a face.
Public static final int flag_ignore_cheek_presses = 0x00008000;

When the request is laid out, your window may appear above or below the status bar, thus blocking. When this option is set, the window manager ensures that the window content is not covered by the decoration bar (status bar.
Public static final int flag_layout_inset_decor = 0x00010000;

Reverse the flag_not_focusable option.
If both the flag_not_focusable option and the current option are set, the window can interact with the input method and allow the input method window to overwrite;
If this option is not set for flag_not_focusable, the window cannot interact with the input method, and the input method window can be overwritten.
Public static final int flag_alt_focusable_im = 0x00020000;

If you have set flag_not_touch_modal, when a touch screen event occurs outside the window, you can receive a motionevent. action_outside event by setting this flag. Note that you will not receive the complete down/move/Up event. You can only receive action_outside when you first go down the event.
Public static final int flag_watch_outside_touch = 0x00040000;

When the screen lock is set, the window is displayed. This gives the application window priority over the screen lock interface. You can use the flag_keep_screen_on option to light up the screen and display it directly before the screen lock. You can use the flag_dismiss_keyguard option to directly unlock the unlocked screen. This option is only used for the top-level full screen window.
Public static final int flag_show_when_locked = 0x00080000;

The request system wallpaper is displayed behind your window. The window must be translucent.
Public static final int flag_show_wallpaper = 0x00100000;

Once the window is displayed, the system will light up the screen, just as the user wakes up the device.
Public static final int flag_turn_screen_on = 0x00200000;

Unlock the screen. Only the screen lock interface is not encrypted can be unlocked. If the screen lock is encrypted, you can see the screen only after unlocking it, unless the flag_show_when_locked option is set.
Public static final int flag_dismiss_keyguard = 0x00400000;

When the screen lock interface fades out, it continues to run its animation.
Public static final int flag_keep_surface_while_animating = 0x10000000;

Display the window in the original size. It is used to run programs in compatible mode.
Public static final int flag_compatible_window = 0x20000000;

Used in the system dialog box. The window for setting this option will obtain the focus unconditionally.
Public static final int flag_system_error = 0x40000000;

7. Public int softinputmode;
Soft input mode options:
The following options are related to softinputmode:
Whether the soft input area is visible.
Public static final int soft_input_mask_state = 0x0f;

The status is not specified.
Public static final int soft_input_state_unspecified = 0;

Do not modify the status of the soft input area.
Public static final int soft_input_state_unchanged = 1;

Hide the Input Method Area (when the user enters the window ).
Public static final int soft_input_state_hidden = 2;

When the window gets focus, the input method area is hidden.
Public static final int soft_input_state_always_hidden = 3;

Display the Input Method Area (when the user enters the window ).
Public static final int soft_input_state_visible = 4;

When the window gets focus, the input method area is displayed.
Public static final int soft_input_state_always_visible = 5;

The window should be adjusted to adapt to the soft input window.
Public static final int soft_input_mask_adjust = 0xf0;

If the status is not specified, the system will try to select an input method style based on the window content.
Public static final int soft_input_adjust_unspecified = 0x00;

When the input method is displayed, the window size can be re-calculated so that the content is not overwritten by the input method.
It cannot be used together with soft_input_adjusp_pan. If neither of them is set, the system automatically sets an option based on the window content.
Public static final int soft_input_adjust_resize = 0x10;

Translation window when the input method is displayed. It does not need to handle size changes. The frame can move the window to ensure that the input focus is visible.
It cannot be used together with soft_input_adjust_resize. If neither of them is set, the system automatically sets an option based on the window content.
Public static final int soft_input_adjust_pan = 0x20;

When you go to this window, it is automatically set by the system, so do not set it.
This flag is automatically cleared when the window is displayed.
Public static final int soft_input_is_forward_navigation = 0x100;

8. Public int gravity;
Gravity attribute. What is the gravity attribute? Simply put, it is how the window is docked.

9. Public float horizontalmargin;
Horizontal margin, the distance between the container and the widget, percentage of the container width.

10. Public float verticalmargin;
Vertical margin.

11. Public int format;
The expected bitmap format. The default value is opacity. See Android. Graphics. pixelformat.

12. Public int windowanimations;
Animation settings used in the window. It must be a system resource rather than an application resource because the window manager cannot access the application.

13. Public float alpha = 1.0f;
The translucent value of the entire window. The value 1.0 indicates opacity, and the value 0.0 indicates full transparency.

14. Public float dimamount = 1.0f;
It takes effect after flag_dim_behind is set. This variable indicates the degree to which the subsequent window is dimmed.
1.0 indicates that the image is completely opaque, and 0.0 indicates that the image is not dimmed.

15. Public float screenbrightness =-1.0f;
It is used to overwrite the screen brightness set by the user. The screen brightness set by the Application User.
The brightness changes from 0 to 1.

16. Public ibinder token = NULL;
The identifier of the window. (Identifier for this window. This will be usually be filled in for you .)

17. Public String packagename = NULL;
The package name of the window.

18. Public int screenorientation = activityinfo. screen_orientation_unspecified;
For more information about the screen direction, see Android. content. PM. activityinfo # screenorientation.

19. The internal buffer used by the backup/recovery parameters in compatibility mode.
Public int [] mcompatibilityparamsbackup = NULL;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.