首先在上節中是使用dialog 實現的,(點擊串連),現在我就講些popupwindow 的實現,這個相對dialog比較簡單,因為不用自訂dialog.
實現代碼很簡單如下:
程式碼片段:
public void showPopupWindow(int x, int y) {layout = (LinearLayout) LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog, null);listView = (ListView) layout.findViewById(R.id.lv_dialog);listView.setAdapter(new ArrayAdapter<String>(MainActivity.this,R.layout.text, R.id.tv_text, title));popupWindow = new PopupWindow(MainActivity.this);popupWindow.setBackgroundDrawable(new BitmapDrawable());popupWindow.setWidth(getWindowManager().getDefaultDisplay().getWidth() / 2);popupWindow.setHeight(300);popupWindow.setOutsideTouchable(true);popupWindow.setFocusable(true);popupWindow.setContentView(layout);// showAsDropDown會把裡面的view作為參照物,所以要那滿螢幕parent// popupWindow.showAsDropDown(findViewById(R.id.tv_title), x, 10);popupWindow.showAtLocation(findViewById(R.id.main), Gravity.LEFT| Gravity.TOP, x, y);//需要指定Gravity,預設情況是center.listView.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {button.setText(title[arg2]);popupWindow.dismiss();popupWindow = null;}});}
button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {button.getTop();int y = button.getBottom() * 3 / 2;int x = getWindowManager().getDefaultDisplay().getWidth() / 4;showPopupWindow(x, y);}});
樣子我就不貼了,和前面一章dialog顯示的一樣.
在這裡遇到個小問題:int y = button.getBottom() * 3 / 2;這裡擷取的y座標應該是 button.getBottom();可是這樣寫popupwindow就顯示位置不對了,在button中間,不知道為什麼。
如果知道為什麼了通知我一下,共同學習嘛,先謝謝了。
/*****************************糾正錯誤**********************************************************/
首先上面int y = button.getBottom() * 3 / 2;
這個是錯誤的,只是偶爾符合了,實際上我少加了18像素.因為少加了一個狀態列 的高度
正確寫法:
Rect frame = new Rect();getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);state_heght = frame.top;// 狀態列的高度int y = button.getBottom()+state_heght ;int x = getWindowManager().getDefaultDisplay().getWidth()/4;showPopupWindow(x, y);
我們看一張圖:
取消狀態列 沒有加狀態列高度 加狀態列高度
其實popupwindow用起來比Dialog 方便,因為dialog一切都需要你自己來實現,而popupwindow幫我們實現了很多,我認為在使用的時候關鍵我們要看清參數:
popupWindow.showAtLocation(parent, gravity, x, y);
parent這個是一個父view試圖,
gravity 這個預設是置中,我們要指定顯示方式:Gravity.LEFT
| Gravity.TOP
最後兩個參數就是顯示的座標位置,這樣就可以根據需求自己定位顯示位置了.
好了,講的不是很詳細,不過之前那個問題解決了,以後在深究吧。
源碼下載