Android的对话框有两种:PopupWindow和AlertDialog。它们的不同点在于:
AlertDialog的位置固定,而PopupWindow的位置可以随意
AlertDialog是非阻塞线程的,而PopupWindow是阻塞线程的
PopupWindow的位置按照有无偏移分,可以分为偏移和无偏移两种;按照参照物的不同,可以分为相对于某个控件(Anchor锚)和相对于父控件。具体如下
showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移
showAsDropDown(View anchor, int xoff, int yoff):相对某个控件的位置,有偏移
showAtLocation(View parent, int gravity, int x, int y):相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移
主界面中定义两个两个界面activity_main.xml和more.xml
activity中定义一个button
more中定义两个button
final Button btn=(Button) findViewById(R.id.start);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btn.setEnabled(false);
//显示more.xml
View view=View.inflate(getApplication(), R.layout.more, null);
//创建PopupWindow对象
popupWindow=new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//获取button的高度
int btnHeight=btn.getHeight();
int btnWidth=btn.getWidth();
//UNSPECIFIED,不指定大小
//at_most,最大
//view中的控件在这里不能直接get,注意
view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int viewWidth=view.getMeasuredWidth();
int viewHeight=view.getMeasuredHeight();
int xOffset=btnWidth;
int yOffset=btnHeight+viewHeight;
popupWindow.showAsDropDown(btn, -xOffset, 0);
Button btnPause=(Button)view.findViewById(R.id.pause);
btnPause.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
}
});