Android中PopupWindow自訂座標實現

來源:互聯網
上載者:User

Android中PopupWindow位置的確定一般通過showAsDropDown函數來實現,該函數有兩個重載函數,分別定義如下:

public void showAsDropDown(View anchor) {<br /> showAsDropDown(anchor, 0, 0);<br /> }</p><p> public void showAsDropDown(View anchor, int xoff, int yoff) {<br /> if (isShowing() || mContentView == null) {<br /> return;<br /> }</p><p> registerForScrollChanged(anchor, xoff, yoff);</p><p> mIsShowing = true;<br /> mIsDropdown = true;</p><p> WindowManager.LayoutParams p = createPopupLayout(anchor.getWindowToken());<br /> preparePopup(p);</p><p> updateAboveAnchor(findDropDownPosition(anchor, p, xoff, yoff));</p><p> if (mHeightMode < 0) p.height = mLastHeight = mHeightMode;<br /> if (mWidthMode < 0) p.width = mLastWidth = mWidthMode;</p><p> p.windowAnimations = computeAnimationResource();</p><p> invokePopup(p);<br /> }

也就是說,調用第一個函數時,x和y座標位移量預設是0,此時PopupWindow顯示的結果如下中圖所示。而要實現PopupWindow顯示在wenwen的正下方時,就需要程式員自己進行座標位移量的計算,下右圖所示,當點擊wenwen時,PopupWindow顯示在正下方,這正是我們所需要的,對稱是一種美啊。




代碼實現的關鍵是點擊wenwen後的響應函數,此處直接上代碼,不廢話了:

public void onClick(View v) {<br />LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);<br />ViewGroup menuView = (ViewGroup) mLayoutInflater.inflate(<br />R.layout.tips, null, true);<br />pw = new PopupWindow(menuView, LayoutParams.WRAP_CONTENT,<br />LayoutParams.WRAP_CONTENT, true);<br />// 設定點擊返回鍵使其消失,且不影響背景,此時setOutsideTouchable函數即使設定為false<br />// 點擊PopupWindow 外的螢幕,PopupWindow依然會消失;相反,如果不設定BackgroundDrawable<br />// 則點擊返回鍵PopupWindow不會消失,同時,即時setOutsideTouchable設定為true<br />// 點擊PopupWindow 外的螢幕,PopupWindow依然不會消失<br />pw.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));<br />pw.setOutsideTouchable(false); // 設定是否允許在外點擊使其消失,到底有用沒?<br />pw.setAnimationStyle(R.style.PopupAnimation); // 設定動畫</p><p>// 計算x軸方向的位移量,使得PopupWindow在Title的正下方顯示,此處的單位是pixels<br />int xoffInPixels = ScreenTools.getInstance(PopDemoActivity.this).getWidth() / 2 - titleName.getWidth() / 2;<br />// 將pixels轉為dip<br />int xoffInDip = ScreenTools.getInstance(PopDemoActivity.this).px2dip(xoffInPixels);<br />pw.showAsDropDown(titleName, -xoffInDip, 0);<br />//pw.showAsDropDown(titleName);<br />pw.update();</p><p>TextView tv = (TextView) menuView.findViewById(R.id.tips_ok);<br />tv.setOnClickListener(new View.OnClickListener() {</p><p>public void onClick(View v) {<br />pw.dismiss();<br />}</p><p>});</p><p>}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.