先拋出問(wèn)題
因?yàn)椴季峙虐嬖颍琓extView并不能完全展示其內(nèi)容,所以出現(xiàn)此需求:點(diǎn)擊TextView在其上方出現(xiàn)一個(gè)氣泡背景來(lái)展示其內(nèi)容。
本來(lái)想著很簡(jiǎn)單的一個(gè)需求动分,首先想到了PopiWindow,用PopuWindow的showAtLocation()去實(shí)現(xiàn)红选,寫(xiě)出了如下代碼澜公。
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);
// 這個(gè)是為了點(diǎn)擊“返回Back”也能使其消失,并且并不會(huì)影響你的背景
popupWindow.setBackgroundDrawable(new BitmapDrawable());
int[] location = new int[2];
//getLocationOnScreen()此函數(shù)可以獲取到View所在視圖的絕對(duì)坐標(biāo)點(diǎn)喇肋,并將獲取到的坐標(biāo)點(diǎn)存放到一個(gè)int數(shù)組中
view.getLocationOnScreen(location);
popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0],location[1] - tv_Content.getHeight());
本以為如此簡(jiǎn)單坟乾,結(jié)果發(fā)現(xiàn)
popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0],location[1] - tv_Content.getHeight());
并未生效(Y軸坐標(biāo)未生效)想到肯定是這里出的問(wèn)題
location[1] - tv_Content.getHeight()
因?yàn)檫@是控制PopuWindow將要出現(xiàn)在Y軸的具體位置,所以想著肯定是
tv_Content.getHeight()沒(méi)獲取到準(zhǔn)確高度
好了蝶防,現(xiàn)在知道問(wèn)題了甚侣,那么直接通過(guò)post()函數(shù)去獲取到tv_Content的高度不就行了嘛,此時(shí)代碼如下:
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);
此時(shí)發(fā)現(xiàn)效果跟之前沒(méi)啥變化慧脱,但是log打印的height是正確的渺绒,想著應(yīng)該是PopuWindow先show后,才獲取到的height菱鸥,所以沒(méi)變化,那好吧我把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);
}
});
此時(shí)發(fā)現(xiàn)效果還是沒(méi)變化氮采,而且離奇的事情發(fā)生了log打印出height的值為0,這是為啥呢染苛?之前還能獲取到的高度這次怎么獲取不到了鹊漠?于是經(jīng)過(guò)兩個(gè)小時(shí)的測(cè)試最終發(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);//此時(shí)讓其顯示出來(lái)
popupWindow.showAtLocation(view, Gravity.NO_GRAVITY,
location[0],location[1] - height);
}
}
});
//PopuWindow第一次show(注意:tv_Content我默認(rèn)是invisible,所以第一次其實(shí)用戶是看不到popu的)
popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0],location[1]);
好了看锉,結(jié)束姿锭。下班Kⅰ!呻此!