Android 為應用增加可移動的懸浮視窗

一葉飄舟發表於2016-01-23

需求描述:
在使用手機客戶端瀏覽內嵌網頁的時候,介面出現一個懸浮的重新整理按鈕,點選網頁重新載入。


佈局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ImageView 
        android:id="@+id/float_fresh"
        android:padding="5dp"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/icon_fresh"
        android:background="@drawable/bg_floatbutton"/>
</LinearLayout>





設定視窗型別在所有視窗之上:

這裡說一下這個LayoutParams.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. In multiuser systems shows on all users' windows.
就是說設定了這個屬性之後,這個視窗會在所以的介面之上,但是在狀態列的下面。在多使用者系統中,所有使用者的視窗上都會顯示。


定義拖動和點選事件:

        mFloatView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub  
					wmParams.x = sWidth - (int) event.getRawX() - mFloatLayout.getMeasuredWidth() / 2;  
	                wmParams.y = sHeight - (int) event.getRawY() - mFloatLayout.getMeasuredHeight() / 2;
	                if(wmParams.y > sHeight - titleHeight){
	                	return true;
	                }
	                 //重新整理  
	                mWindowManager.updateViewLayout(mFloatLayout, wmParams); 
	                return false;
			}
		});
        
        mFloatView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				web.reload();
			}
		});

別忘了許可權宣告:

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


效果圖:


相關文章