標籤:
經常,我們看到在案頭上可移動的懸浮窗,這種情境還是很多的, 像流量統計,案頭歌詞等,安全軟體的清理小組件
這種小組件主要是通過 WindowManager ; WindowManager.LayoutParams 這兩個類來實現
調用 WindowManager 的addView(view, params)方法來添加一個懸浮窗.updateViewLayout(view,params)來更新懸浮窗參數.removeView(view)用於移除懸浮窗
WindowManager.LayoutParams 主要是用來提供參數的
其中的參數有type: 懸浮窗的類型,通常設定為2002, 即在所有程式之上.狀態列之下
flags :用於確定懸浮窗的行為
gravity : 用於確定懸浮窗的對其方式
x: 懸浮窗的橫向座標
y: 懸浮窗的縱向座標
width: 懸浮窗的寬度
height : 懸浮窗的高度
建立懸浮窗需要添加許可權:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
懸浮窗布局
<?xml version="1.0" encoding="UTF-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/small_window_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/bg" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="拖拽移動.." android:textSize="20sp" /></LinearLayout>
建立一個類繼承Application,Application就是應用的進入點,寫在這裡,就是程式一運行,就會出來
同時,需要在資訊清單檔的Application結點上配置名稱
package com.example.windowmanagerdemo;import android.annotation.SuppressLint;import android.app.Application;import android.content.Context;import android.graphics.PixelFormat;import android.view.LayoutInflater;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;import android.view.WindowManager;import android.view.WindowManager.LayoutParams;public class MAppliction extends Application { WindowManager mWM; WindowManager.LayoutParams mParams; @Override public void onCreate() { super.onCreate(); mWM = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE); mParams = new WindowManager.LayoutParams(); final View mwm = LayoutInflater.from(this).inflate(R.layout.mwm, null); mwm.setOnTouchListener(new OnTouchListener() { float lastX, lastY; @SuppressLint("NewApi") @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = event.getX(); lastY = event.getY(); break; case MotionEvent.ACTION_MOVE: float moveX = event.getX(); float moveY = event.getY(); mParams.x += (int) (moveX - lastX); mParams.y += (int) (moveY - lastY); mWM.updateViewLayout(mwm, mParams); break; default: break; } return true; } }); mParams.type = LayoutParams.TYPE_PHONE; mParams.format = PixelFormat.RGBA_8888; mParams.width = 50; mParams.height = 30; mWM.addView(mwm, mParams); }}
Android案頭懸浮窗