android popupwindow 调用方法,Android PopUpWindow使用详解
釋放雙眼,帶上耳機,聽聽看~!
一、概述
1、PopupWindow與AlertDialog的區別
最關鍵的區別是AlertDialog不能指定顯示位置,只能默認顯示在屏幕最中間(當然也可以通過設置WindowManager參數來改變位置)。而PopupWindow是可以指定顯示位置的,隨便哪個位置都可以,更加靈活。
2、PopupWindow的相關函數
第一步:最基本構造PopupWindow
View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popuplayout, null);
PopupWindwo popWnd = PopupWindow (context);
popWnd.setContentView(contentView);
popWnd.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
popWnd.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
拓展:也可以縮寫成為兩句話
View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popuplayout, null);
PopupWindwo popWnd = new PopupWindow (contextView,ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
第二步:上面的代碼基本就生成了一個簡單的PopUpWindow,但是想要顯示出來還需要以下方法
顯示函數主要使用下面三個:
//相對某個控件的位置(正左下方),無偏移
showAsDropDown(View anchor):
//相對某個控件的位置,有偏移;xoff表示x軸的偏移,正值表示向左,負值表示向右;yoff表示相對y軸的偏移,正值是向下,負值是向上;
showAsDropDown(View anchor, int xoff, int yoff):
//相對于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以設置偏移或無偏移
showAtLocation(View parent, int gravity, int x, int y):
這里有兩種顯示方式:
1、顯示在某個指定控件的下方
showAsDropDown(View anchor):
showAsDropDown(View anchor, int xoff, int yoff);
2、指定父視圖,顯示在父控件的某個位置(Gravity.TOP,Gravity.RIGHT等)
showAtLocation(View parent, int gravity, int x, int y);
第三步顯示窗體
通過showAsDropDown顯示出來,但是從哪里顯示出來還沒有定義,
有同學就會問難道不是在第一步布局文件顯示的嗎?
那只是顯示的布局,并沒有說在哪里顯示,所以我們還是要加載主窗口,在主窗口顯示
View rootview = LayoutInflater.from(MainActivity.this).inflate(R.layout.main, null);
mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);
完整代碼
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.pewm, null);
mPopWindow = new PopupWindow(contentView,
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
//顯示PopupWindow
View rootview = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);
}
總結
以上是生活随笔為你收集整理的android popupwindow 调用方法,Android PopUpWindow使用详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牛顿简介
- 下一篇: 16.04编译android 7.0,u