1、PopupWindow与AlertDialog的区别
最关键的区别是AlertDialog不能指定显示位置,只能默认显示在屏幕最中间(当然也可以通过设置WindowManager参数来改变位置)。而PopupWindow是可以指定显示位置的,随便哪个位置都可以,更加灵活。有关Dialog的相关知识,大家可以参考我的系列博客: 《详解Dialog(一)——基础元素构建》
2、PopupWindow的相关函数
(1)、构造函数:
首要注意:看这里有四个构造函数,但要生成一个PopupWindow最基本的三个条件是一定要设置的:View contentView,int width, int height ;少任意一个就不可能弹出来PopupWindow!!!!所以,如果使用方法一来构造PopupWindow,那完整的构造代码应该是这样的:
有关为什么一定要设置width和height的原因,我们后面会讲,这里说一下为什么样强制设置contentView;很简单的原因是因为PopupWindow没有默认布局,它不会像AlertDialog那样只setTitle,就能弹出来一个框。PopupWindow是没有默认布局的,它的布局只有通过我们自己设置才行。由于方法三中,含有了这三个必备条件,不用单独设置contentview或者width、height,所以构造方法三是用的最多的一个构造方法。
最后,方法四中的focusable变量不是必须的,有关它的方法和意义,我们会在下一篇中细讲。
(2)显示函数
显示函数主要使用下面三个:
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);
(3)、其它函数
public class MainActivity extends AppCompatActivity{ private Button button; private PopupWindow popupWindow; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); View view = LayoutInflater.from(this).inflate(R.layout.popuwindow,null); popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT,false); initView(); } private void initView() { button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onClick(View view) { if (popupWindow.isShowing()){ popupWindow.dismiss(); }else { //显示在父级控件的下方 popupWindow.showAtLocation(view,Gravity.BOTTOM,0,0); //显示在本控件的下方 // popupWindow.showAsDropDown(view,0,0,Gravity.BOTTOM); } } }); } }