Android 6.0之前 建立window方法如下:

weixin_34321977發表於2018-05-10

Android 6.0之前 建立window方法如下:

@SuppressWarnings("rawtypes")
Class policyManagerClass = Class.forName("com.android.internal.policy.PolicyManager");
@SuppressWarnings("rawtypes")
Class[] parameterTypes = { Context.class };
Method method = policyManagerClass.getMethod("makeNewWindow", parameterTypes);
mWindow = (Window) method.invoke(null, mContext);

Android 6.0 以及後續版本,com.android.internal.policy.PolicyManager 已經被刪除,所以建立window方法如下:

方法一
Dialog dialog  = new Dialog(mContext);
mWindow = dialog.getWindow();

方法二,此方法不適合非手機端
Class windowClass = Class.forName("com.android.internal.policy.PhoneWindow");
Constructor<?> localConstructor = windowClass.getConstructor(new Class[]{Context.class});
mWindow = (Window) localConstructor.newInstance(new Object[]{mContext});

完整程式碼為:

private void initWindow() {
    try {
        Dialog dialog  = new Dialog(mContext);
        mWindow = dialog.getWindow();
        mWindow.setFormat(PixelFormat.TRANSLUCENT);
        mWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        mWindow.requestFeature(Window.FEATURE_NO_TITLE);
        mWindow.setSoftInputMode(LayoutParams.SOFT_INPUT_ADJUST_RESIZE | LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        mWindow.setWindowManager(wm, null, null);
        colorDrawable = new ColorDrawable();
        colorDrawable.setAlpha(0);
        mWindow.setBackgroundDrawable(colorDrawable);
        mWindow.setCallback(this);
        defindedView = new DefindedView(mContext);
        defindedView.addView(mView);
        mWindow.setContentView(defindedView.getView());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

參考

https://www.jianshu.com/p/4a1c35a17fe5

相關文章