1.PopupWindow常用方法
public void method() {
popupWindow.dismiss();//popupWindow消失
popupWindow.getContentView();//得到popupWindow设置的view
popupWindow.isShowing();//是否显示
popupWindow.setAnimationStyle(animationStyle)//设置动画样式
popupWindow.showAsDropDown(anchorView);
popupWindow.showAsDropDown(anchorView, xoff, yoff);
popupWindow.showAtLocation(parent, gravity, x, y);
}
2.简单PopupWindow实例
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = getLayoutInflater().inflate(R.layout.item, null);
popupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
}
/** 显示在View v的下方 */
public void show1(View v) {
if (popupWindow.isShowing()) {
popupWindow.dismiss();
} else {
popupWindow.showAsDropDown(v);
}
}
3.自定义动画
popupWindow.setAnimationStyle(R.style.style_popup_anim);
popupWindow.showAsDropDown(v);
4.PopupWindow置于控件上方
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = getLayoutInflater().inflate(R.layout.item, null);
popupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
// 计算view的宽高
getWidthAndHeight(view);
}
@Override
public void onClick(View v) {
if (popupWindow.isShowing()) {
popupWindow.dismiss();
} else {
//设置动画样式,自下往上
popupWindow.setAnimationStyle(R.style.style_popup_anim);
//得到view 左上点在屏幕中的位置
int[] location = new int[2];
v.getLocationOnScreen(location);
popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0],
location[1] - height);
}
}
// 得到View宽高
public void getWidthAndHeight(View view) {
int widthSpec = View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED);
int heightSpec = View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED);
view.measure(widthSpec, heightSpec);
width = view.getMeasuredWidth();
height = view.getMeasuredHeight();
}