有時候需要在顯示UI的時候不中斷原來的Activity
比如在播放視頻時或者玩游戲時,需要顯示某個菜單(可以是系統(tǒng)提示,或類似于TV菜單)
顯然用Activity來做是不行的,因?yàn)樾翧ctivity啟動的時候會把原來的Activity pause掉
怎么做呢,可以參考系統(tǒng)電量提示窗口或statusbar那樣在service中啟動窗口
新窗口將會出現(xiàn)在UI最上層,但不會中斷原來的Activity
效果圖,一個是播視頻中,一個是玩游戲中:
看一下WindowManager.LayoutParams的兩個屬性:
int TYPE_SYSTEM_ALERT Window type: system window, such as low power alert.
int TYPE_SYSTEM_OVERLAYWindow type: system overlay windows, which need to be displayed on top of everything else.
這兩個不錯,正是我們想要的,上代碼~
Seivece中代碼
- private void showSystemDialog() {
- /* create ui */
- View v = View.inflate(mContext, R.layout.main, null);
- AlertDialog.Builder b = new AlertDialog.Builder(mContext);
- b.setView(v);
- d = b.create();
- d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
- //d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY);
- d.show();
-
- /* set size & pos */
- WindowManager.LayoutParams lp = d.getWindow().getAttributes();
- WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
- Display display = wm.getDefaultDisplay();
- if (display.getHeight() > display.getWidth()) {
- //lp.height = (int) (display.getHeight() * 0.5);
- lp.width = (int) (display.getWidth() * 1.0);
- } else {
- //lp.height = (int) (display.getHeight() * 0.75);
- lp.width = (int) (display.getWidth() * 0.5);
- }
- d.getWindow().setAttributes(lp);
-
- /* update ui data */
- lv = (ListView) d.getWindow().findViewById(R.id.listview);
- SimpleAdapter adapter = new SimpleAdapter(mContext, getListData(), R.layout.list_item,
- new String[]{"item_text", "item_img"},
- new int[]{R.id.item_text, R.id.item_img});
- lv.setAdapter(adapter);
-
- /* set listener */
- lv.setOnItemClickListener(new OnItemClickListener() {
- public void onItemClick(AdapterView<?> parent, View view, int pos,
- long id) {
- d.dismiss();
- }
- });
-
- }
創(chuàng)建了一個dialog,可以調(diào)整dialog的位置、大小,dialog的從R.layout.main創(chuàng)建,動態(tài)添加UI數(shù)據(jù)
響應(yīng)Ui上的OnClick操作
* manifest中需要相應(yīng)的permission
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
* TYPE_SYSTEM_ALERT跟TYPE_SYSTEM_OVERLAY的區(qū)別
以上面的代碼為例,system_alert窗口可以獲得焦點(diǎn),響應(yīng)操作
system_overlay窗口顯示的時候焦點(diǎn)在后面的Activity上,仍舊可以操作后面的Activity
* 上面的代碼中請留意d.show()的位置,只有在show之后才能調(diào)整dialog大小及更新數(shù)據(jù)
* 可以調(diào)整的Attributes,先dump出來
lp.flags = 0x20002, // FLAG_DIM_BEHIND | FLAG_ALT_FOCUSABLE_IM
lp.gravity = 0x11, // CENTER
lp.type = 0x7d3, // TYPE_SYSTEM_ALERT
這些Attr都可以設(shè)置,具體定義在API文檔WindowManager.LayoutParams中
|