先拋出問題
因為布局排版原因,TextView并不能完全展示其內(nèi)容,所以出現(xiàn)此需求:點擊TextView在其上方出現(xiàn)一個氣泡背景來展示其內(nèi)容。
本來想著很簡單的一個需求,首先想到了PopiWindow,用PopuWindow的showAtLocation()去實現(xiàn),寫出了如下代碼。
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View inflate = layoutInflater.inflate(R.layout.popupwindow_layout, null);
TextView tv_Content = (TextView) inflate.findViewById(R.id.tv_Content);
PopupWindow popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv_Content.setText(content);
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
// 這個是為了點擊“返回Back”也能使其消失,并且并不會影響你的背景
popupWindow.setBackgroundDrawable(new BitmapDrawable());
int[] location = new int[2];
//getLocationOnScreen()此函數(shù)可以獲取到View所在視圖的絕對坐標(biāo)點,并將獲取到的坐標(biāo)點存放到一個int數(shù)組中
view.getLocationOnScreen(location);
popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0],location[1] - tv_Content.getHeight());
本以為如此簡單,結(jié)果發(fā)現(xiàn)
popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0],location[1] - tv_Content.getHeight());
并未生效(Y軸坐標(biāo)未生效)想到肯定是這里出的問題
location[1] - tv_Content.getHeight()
因為這是控制PopuWindow將要出現(xiàn)在Y軸的具體位置,所以想著肯定是
tv_Content.getHeight()沒獲取到準(zhǔn)確高度
好了,現(xiàn)在知道問題了,那么直接通過post()函數(shù)去獲取到tv_Content的高度不就行了嘛,此時代碼如下:
tv_Content.post(new Runnable() {
@Override
public void run() {
mHeight = tv_Content.getMeasuredHeight();
Log.e("TAG","post>>>>" + height);
}
});
popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0],location[1] - mHeight);
此時發(fā)現(xiàn)效果跟之前沒啥變化,但是log打印的height是正確的,想著應(yīng)該是PopuWindow先show后,才獲取到的height,所以沒變化,那好吧我把PopuWindow放在post里面show總行了吧。
tv_Content.post(new Runnable() {
@Override
public void run() {
int height = tv_Content.getMeasuredHeight();
Log.e("TAG","post>>>>" + height);
popupWindow.showAtLocation(view, Gravity.NO_GRAVITY,
location[0],location[1] - height);
}
});
此時發(fā)現(xiàn)效果還是沒變化,而且離奇的事情發(fā)生了log打印出height的值為0,這是為啥呢?之前還能獲取到的高度這次怎么獲取不到了?于是經(jīng)過兩個小時的測試最終發(fā)現(xiàn)。。。。
PopupWindow未show之前,其內(nèi)部的View是獲取不到寬高的。
于是最終修改為:
tv_Content.post(new Runnable() {
@Override
public void run() {
int height = tv_Content.getMeasuredHeight();
Log.e("TAG","post>>>>" + height);
if (popupWindow.isShowing()){
popupWindow.dismiss();
tv_Content.setVisibility(View.VISIBLE);//此時讓其顯示出來
popupWindow.showAtLocation(view, Gravity.NO_GRAVITY,
location[0],location[1] - height);
}
}
});
//PopuWindow第一次show(注意:tv_Content我默認(rèn)是invisible,所以第一次其實用戶是看不到popu的)
popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0],location[1]);
好了,結(jié)束。下班!??!