做完一個app之后發(fā)現(xiàn)給視圖增加全屏的蒙層是很常用的一個功能奠旺,之前是在BaseActiviy中寫死一個全屏的view宦棺,在子類中控制其顯示,這樣會大大增加基類中的代碼量箕戳,于是查詢在當前類中通過代碼來增加蒙層的方法某残,如下:
public void showGuideView() {
View view = getWindow().getDecorView().findViewById(R.id.activity_main);
if (view == null) return;
ViewParent viewParent = view.getParent();
if (viewParent instanceof FrameLayout) {
final FrameLayout frameParent = (FrameLayout) viewParent;//整個父布局
final LinearLayout linearLayout = new LinearLayout(this);//新建一個LinearLayout
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setBackgroundColor(#88000000);//背景設置灰色透明
linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
frameParent.removeView(linearLayout);
}
});
Rect rect = new Rect();
Point point = new Point();
nearby.getGlobalVisibleRect(rect, point);//獲得nearby這個控件的寬高以及XY坐標 nearby這個控件對應就是需要高亮顯示的地方
ImageView topGuideview = new ImageView(this);
topGuideview.setLayoutParams(new ViewGroup.LayoutParams(rect.width(), rect.height())); topGuideview.setBackgroundResource(R.drawable.iv_topguide);
Rect rt = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(rt);
topGuideview.setY(point.y - rt.top);//rt.top是手機狀態(tài)欄的高度
ImageView bottomGuideview = new ImageView(this);
bottomGuideview.setLayoutParams(new ViewGroup.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
bottomGuideview.setBackgroundResource(R.drawable.iv_bottomguide);
bottomGuideview.setY(point.y + topGuideview.getHeight());
linearLayout.addView(topGuideview);
linearLayout.addView(bottomGuideview);
frameParent.addView(linearLayout);
}
}
參考文章
https://blog.csdn.net/u013299273/article/details/54137847
https://blog.csdn.net/qq_31743309/article/details/77934273
https://blog.csdn.net/Dreamj1991/article/details/80267464