安卓可移動的懸浮窗口的使用

需求描述:

在使用手機客戶端瀏覽內嵌網頁的時候,界面出現一個懸浮的刷新按鈕,點擊網頁重新加載。


定義窗口布局:

<?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對象
        wmParams = new WindowManager.LayoutParams();
        
        //獲取的是LocalWindowManager對象
        wmParams.type = LayoutParams.TYPE_PHONE;
        wmParams.format = PixelFormat.RGBA_8888;//背景透明
        wmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE;//如果沒有這句話的話,在生成懸浮窗口後,懸浮窗口後的界面上東西都不能點。這句話的目的是讓懸浮窗口失去焦點。

這裏說一下這個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" />


效果圖:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章