不依賴Activity、Dialog顯示View方法

一、首先我們先看下Activity是如何顯示View
平常我們在Activity的onCreate會調(diào)用setContentView(R.layout.xxx)臂港,Activity啟動過程與window的源碼流程可參考
Activity Window WMS的源碼關(guān)系流程介紹
總結(jié)幾個步驟:
1卿捎、創(chuàng)建Activity:ActivityThread的performLaunchActivity函數(shù)中創(chuàng)建Activity后配紫,調(diào)用Activity.attach函數(shù)
2、創(chuàng)建PhoneWindow:Activity.attach函數(shù)中創(chuàng)建與之關(guān)聯(lián)的PhoneWindow,PhoneWindow會創(chuàng)建DectorView午阵。
3躺孝、添加視圖:setContentView添加到PhoneWindow的DectorView中
4、關(guān)聯(lián)PhoneWindow到WMS中:ActivityThread實(shí)行完performLaunchActivity底桂,會handleResumeActivity植袍,走到Activity的onResume,然后設(shè)置Activity的PhoneWindow的type類型:

final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
            .....
            if (r.window == null && !a.mFinished && willBeVisible) {
                r.window = r.activity.getWindow();
                View decor = r.window.getDecorView();
                decor.setVisibility(View.INVISIBLE);
                ViewManager wm = a.getWindowManager();
                WindowManager.LayoutParams l = r.window.getAttributes();
                a.mDecor = decor;
                l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                l.softInputMode |= forwardBit;
              ...
            } 
}

PhoneWindow會創(chuàng)建DectorView籽懦,通過WindowManagerImpl-->WindowManagerGlobal-->ViewRootImpl-->(binder)WMS中的Session的addToDisplay函數(shù)于个,這樣視圖就會顯示出來。
我們看下l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;

WindowManager.java:

public interface WindowManager extends ViewManager {
/**
  * Window type: an application window that serves as the "base" window
  * of the overall application; all other application windows will
  * appear on top of it.
  * In multiuser systems shows only on the owning user's window.
*/
  public static final int TYPE_BASE_APPLICATION   = 1;
}

從英文翻譯來看暮顺,這個type是應(yīng)用程序的window類型厅篓。

二、Dialog顯示View:

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setMessage("Message部分");
        builder.setTitle("Title部分");
        builder.setView(R.layout.dialog_main);
        builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
            }
        });
        alertDialog = builder.create();
        alertDialog.show();

我們順著alertDialog.show():

public AlertDialog create() {
            // Context has already been wrapped with the appropriate theme.
            final AlertDialog dialog = new AlertDialog(P.mContext, 0, false);
            P.apply(dialog.mAlert);
            dialog.setCancelable(P.mCancelable);
            if (P.mCancelable) {
                dialog.setCanceledOnTouchOutside(true);
            }
            dialog.setOnCancelListener(P.mOnCancelListener);
            dialog.setOnDismissListener(P.mOnDismissListener);
            if (P.mOnKeyListener != null) {
                dialog.setOnKeyListener(P.mOnKeyListener);
            }
            return dialog;
        }

其中final AlertDialog dialog = new AlertDialog(P.mContext, 0, false);

protected AlertDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        this(context, 0);
        setCancelable(cancelable);
        setOnCancelListener(cancelListener);
    }
    AlertDialog(Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
        super(context, createContextThemeWrapper ? resolveDialogTheme(context, themeResId) : 0,
                createContextThemeWrapper);
        mWindow.alwaysReadCloseOnTouchAttr();
        mAlert = new AlertController(getContext(), this, getWindow());
}

super是Dialog捶码,接著看Dialog的構(gòu)造函數(shù):

Dialog(@NonNull Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
        ...
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        final Window w = new PhoneWindow(mContext);
        mWindow = w;
        w.setCallback(this);
        w.setOnWindowDismissedCallback(this);
        w.setWindowManager(mWindowManager, null, null);
        w.setGravity(Gravity.CENTER);
        mListenersHandler = new ListenersHandler(this);
    }

這邊會創(chuàng)建Dialog的PhoneWindow羽氮,我們看PhoneWindow的構(gòu)造函數(shù)

public PhoneWindow(Context context) {
        super(context);
        mLayoutInflater = LayoutInflater.from(context);
    }

父類Window的

public abstract class Window {
// The current window attributes.
    private final WindowManager.LayoutParams mWindowAttributes =
        new WindowManager.LayoutParams();
//默認(rèn)的PhoneWindow類型
public Window(Context context) {
        mContext = context;
        mFeatures = mLocalFeatures = getDefaultFeatures(context);
    }
}

看WindowManager.LayoutParams:

public LayoutParams() {
            super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            type = TYPE_APPLICATION;
            format = PixelFormat.OPAQUE;
        }

這個type的默認(rèn)window類型是TYPE_APPLICATION:

      /**
         * Window type: a normal application window.  The {@link #token} must be
         * an Activity token identifying who the window belongs to.
         * In multiuser systems shows only on the owning user's window.
         */
        public static final int TYPE_APPLICATION        = 2;

這個Dialog的window就需要依賴Activity來顯示了。
三惫恼、直接使用系統(tǒng)級的Window類型档押,來添加View:

WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
layoutParams.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_FULLSCREEN;
layoutParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
layoutParams.gravity = Gravity.CENTER;
layoutParams.x = 0;
layoutParams.y = 0;
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.format = PixelFormat.TRANSPARENT;
LayoutInflater layoutInflater = (LayoutInflater) LayoutInflater.from(context);
View view = (View) layoutInflater.inflate(R.layout.window_test_main, null);
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.addView(view, layoutParams);

這個context上下文可以是service、application的祈纯。
其中l(wèi)ayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;

/**
         * Window type: internal system error windows, appear on top of
         * everything they can.
         * In multiuser systems shows only on the owning user's window.
         */
        public static final int TYPE_SYSTEM_ERROR       = FIRST_SYSTEM_WINDOW+10;

這是系統(tǒng)級的window

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末令宿,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子盆繁,更是在濱河造成了極大的恐慌掀淘,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件油昂,死亡現(xiàn)場離奇詭異革娄,居然都是意外死亡倾贰,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進(jìn)店門拦惋,熙熙樓的掌柜王于貴愁眉苦臉地迎上來匆浙,“玉大人,你說我怎么就攤上這事厕妖∈啄幔” “怎么了?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵言秸,是天一觀的道長软能。 經(jīng)常有香客問我,道長举畸,這世上最難降的妖魔是什么查排? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮抄沮,結(jié)果婚禮上跋核,老公的妹妹穿的比我還像新娘。我一直安慰自己叛买,他們只是感情好砂代,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著率挣,像睡著了一般刻伊。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上难礼,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天娃圆,我揣著相機(jī)與錄音,去河邊找鬼蛾茉。 笑死,一個胖子當(dāng)著我的面吹牛撩鹿,可吹牛的內(nèi)容都是我干的谦炬。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼节沦,長吁一口氣:“原來是場噩夢啊……” “哼键思!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起甫贯,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤吼鳞,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后叫搁,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體赔桌,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡供炎,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了疾党。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片音诫。...
    茶點(diǎn)故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖雪位,靈堂內(nèi)的尸體忽然破棺而出竭钝,到底是詐尸還是另有隱情,我是刑警寧澤雹洗,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布香罐,位于F島的核電站,受9級特大地震影響时肿,放射性物質(zhì)發(fā)生泄漏庇茫。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一嗜侮、第九天 我趴在偏房一處隱蔽的房頂上張望港令。 院中可真熱鬧,春花似錦锈颗、人聲如沸顷霹。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽淋淀。三九已至,卻和暖如春覆醇,著一層夾襖步出監(jiān)牢的瞬間朵纷,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工永脓, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留袍辞,地道東北人。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓常摧,卻偏偏與公主長得像搅吁,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子落午,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容