<p>在Android 界面組成一文中秉沼,描述說DecorView是一個FrameLayout胸遇,其中在PhoneWindow中還包含了一個mContentParent
,是對DecorView布局中的ID 為 content的FrameLayout的實例化吨述,因此我們可以通過對mContentParent 進(jìn)行addView操作具伍,將一個View繪制在Activity上層</p>
1.獲取DecorView
View decorView = getWindow().getDecorView();
2.獲取ContentParent
FrameLayout contentParent =
(FrameLayout) decorView.findViewById(android.R.id.content);
3.將View添加到contentParent上
TextView x = new TextView(this);
x.setText("這是一個TextView\n通過DecorView將其繪制到了Activity上層");
x.setGravity(Gravity.CENTER);
x.setBackgroundColor(Color.RED);
x.setLayoutParams(
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
200));
contentParent.addView(x);
4.運行結(jié)果
Paste_Image.png
Tips
getWindow是Acticity的方法,在Service/BroadCastRceiver中無法獲取纵散,通樣也不能操作UI