本文實(shí)例講述了Android中懸浮窗口的實(shí)現(xiàn)原理。分享給大家供大家參考。具體如下:
用了我一個(gè)周末的時(shí)間,個(gè)中憤懣就不說(shuō)了,就這個(gè)問(wèn)題,我翻遍全球網(wǎng)絡(luò)沒(méi)有一篇像樣的資料,現(xiàn)在將實(shí)現(xiàn)原理簡(jiǎn)單敘述如下:
調(diào)用WindowManager,并設(shè)置WindowManager.LayoutParams的相關(guān)屬性,通過(guò)WindowManager的addView方法創(chuàng)建View,這樣產(chǎn)生出來(lái)的View根據(jù)WindowManager.LayoutParams屬性不同,效果也就不同了。比如創(chuàng)建系統(tǒng)頂級(jí)窗口,實(shí)現(xiàn)懸浮窗口效果!
WindowManager的方法很簡(jiǎn)單,基本用到的就三個(gè)addView,removeView,updateViewLayout。
而WindowManager.LayoutParams的屬性就多了,非常豐富,具體請(qǐng)查看SDK文檔。這里給出Android中的WindowManager.java源碼,可以具體看一下。
下面是簡(jiǎn)單示例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class myFloatView extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); Button bb= new Button(getApplicationContext()); WindowManager wm=(WindowManager)getApplicationContext().getSystemService( "window" ); WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams(); /** *以下都是WindowManager.LayoutParams的相關(guān)屬性 * 具體用途請(qǐng)參考SDK文檔 */ wmParams.type= 2002 ; //這里是關(guān)鍵,你也可以試試2003 wmParams.format= 1 ; /** *這里的flags也很關(guān)鍵 *代碼實(shí)際是wmParams.flags |= FLAG_NOT_FOCUSABLE; *40的由來(lái)是wmParams的默認(rèn)屬性(32)+ FLAG_NOT_FOCUSABLE(8) */ wmParams.flags= 40 ; wmParams.width= 40 ; wmParams.height= 40 ; wm.addView(bb, wmParams); //創(chuàng)建View } } |
別忘了在AndroidManifest.xml中添加權(quán)限:
PS:這里舉例說(shuō)明一下type的值的意思:
1
2
3
4
|
/** * 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 ; |
這個(gè)FIRST_SYSTEM_WINDOW的值就是2000。2003和2002的區(qū)別就在于2003類(lèi)型的View比2002類(lèi)型的還要top,能顯示在系統(tǒng)下拉狀態(tài)欄之上!
希望本文所述對(duì)大家的Android程序設(shè)計(jì)有所幫助。