FloatUtil
一個簡單的浮窗工具。封裝了浮窗的使用方法,并做了系統(tǒng)、版本的兼容處理,幫你繞過權(quán)限的限制。
float_drag.gif
開始
項目使用 jitpack 做開源庫的托管,你需要在 .gradle 中添加 jitpack
的倉庫。
allprojects {
repositories {
jcenter()
maven { url "https://jitpack.io" }
}
}
在添加 FloatUtil 的依賴引用:
dependencies {
compile 'com.github.liuguangli:FloatUtil:master-SNAPSHOT'
}
創(chuàng)建一個簡單的浮窗
SimpleView floatView = new SimpleView(this);
FloatUtil.showFloatView(floatView, null);
SimpleView 是你自定義的 View,就這么簡單,浮窗顯示出來了。
simple_float.gif
關(guān)閉浮窗
FloatUtil.hideFloatView(context, SimpleView.class, false);
z同一個 View 類,同時只能顯示一個實例, 關(guān)閉的時候指定一個 class 對象便能知道關(guān)閉哪個浮窗實例。 最后一個參數(shù)
決定要不要將當(dāng)前實例緩存,以便下次快速顯示并維持狀態(tài),false 代表不緩存,true 表示要緩存。
向浮窗傳遞參數(shù)
FloatUtil 提供了一個接口:ParamReceiver。你自定義的 View 實現(xiàn)這個接口便能接收參數(shù)。
public class SimpleViewWitchParam extends FrameLayout implements ParamReceiver {
public static final java.lang.String PARAM = "PARAM";
public static final String CONTENT = "content";
@Override
public void onParamReceive(Bundle bundle) {
// 在這個回調(diào)方法中接收參數(shù)并解析
if (bundle != null) {
String param = bundle.getString(PARAM);
}
}
}
然后在添加這個 SimpleViewWitchParam 到浮窗。
SimpleViewWitchParam floatView = new SimpleViewWitchParam(this);
Bundle bundle = new Bundle();
bundle.putString(SimpleViewWitchParam.PARAM, "我是傳過來的參數(shù)");
FloatUtil.showFloatView(floatView, bundle);
float_param.gif
指定層級和對齊方式
SimpleViewWitchParam floatView = new SimpleViewWitchParam(this);
// 居中對齊,浮窗層級為 WindowManager.LayoutParams.TYPE_TOAST
FloatUtil.showFloatView(floatView, Gravity.CENTER,WindowManager.LayoutParams.TYPE_TOAST , null);
float_center.gif
浮窗類型 type 決定了浮窗的層級,關(guān)于浮窗層級的詳細(xì)理解可以參考我的博客:《浮窗開發(fā)之窗口層級》,
Android 系統(tǒng)對窗體的某些層級有權(quán)限限制,例如 WindowManager.LayoutParams.TYPE_PHONE 類型的窗體需要授權(quán)。
智能浮窗(突破授權(quán))
FloatUtil 提供智能方式添加浮窗,針對特定的系統(tǒng)版本、機(jī)型為你選擇合適的浮窗 type ,越過授權(quán)(詳細(xì)參考我的博客:越過用戶授權(quán)使用浮窗),你不需要再去關(guān)注復(fù)雜的處理過程。
SimpleViewWitchParam floatView = new SimpleViewWitchParam(this);
Bundle bundle = new Bundle();
bundle.putString(SimpleViewWitchParam.PARAM, "智能浮窗");
// 指定浮窗顯示的位置
Point point = new Point();
point.x = 0;
point.y = 0;
FloatUtil.showSmartFloat(floatView, Gravity.CENTER, point, bundle);