1. Activity
覆寫 onWindowFocusChanged(boolean hasFocus)方法奈虾。
@Override public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
/* 獲取在當(dāng)前窗口內(nèi)的絕對(duì)坐標(biāo) */
int[] location1 = new int[2] ;
view.getLocationInWindow(location1);
/*獲取在整個(gè)屏幕內(nèi)的絕對(duì)坐標(biāo)*/
int[] location2 = new int[2] ;
view.getLocationOnScreen(location2);
doSomething();
}
}
2. Fragment
在 onCreateView()中通過(guò)ViewTreeObserver為View注冊(cè)addOnGlobalLayoutListener()接口回調(diào)。
private View view;
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.xxx, container, false);
ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override public void onGlobalLayout() {
/* 獲取子控件信息 */
doGetInfo();
/* 獲取子控件信息后惩嘉,注銷回調(diào)用接口 */
view.getViewTreeObserver().removeOnGlobalLayoutListener(this); } });
doSomething();
return view;
}
注:因?yàn)楫?dāng)在一個(gè)視圖樹(shù)中全局布局發(fā)生改變或者視圖樹(shù)中的某個(gè)視圖的可視狀態(tài)發(fā)生改變時(shí)殖属,OnGlobalLayoutListener就會(huì)被觸發(fā)鲁豪,所以此接口的回調(diào)函數(shù)可能會(huì)被多次調(diào)用光涂,因此在得到了高度之后日杈,要將OnGlobalLayoutListener注銷掉遣铝。