很简单的一个自定义的popwindown的基本类,主要功能是在任意布局的上下左右弹出pop对话框,如果不够用,自己修改代码在任意位置弹出pop窗口,也很简单。
<span style="font-size:18px;">public class BaseCustomPop extends PopupWindow {
private View rootView;//pop的布局
private int[] location = new int[2];
private int margin = 10;//pop与控件的距离间隔
public BaseCustomPop(View view) {
this(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
public BaseCustomPop(View view, int width, int height) {
this(view, width, height, 0);
}
/**
* @param layoutView
* @param width
* @param height
* @param animationStyle
*/
public BaseCustomPop(View layoutView, int width, int height, int animationStyle) {
// setAnimationStyle(R.style.pop_anim);
this.setWidth(width);
this.setHeight(height);
this.rootView = layoutView;
this.setAnimationStyle(animationStyle);
this.setFocusable(true);
this.setOutsideTouchable(true);
this.setBackgroundDrawable(new BitmapDrawable());
this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
this.setContentView(layoutView);
}
public void show(View anchor) {
show(anchor, POPGriVity.TOP);
}
public enum POPGriVity {
TOP, BOTTOM, LEFT, RIGHT
}
public void setMargin(int margin) {
this.margin = margin;
}
public void show(View anchor, POPGriVity grivity) {
if (rootView == null)
throw new IllegalStateException("setContentView was not called with a view to display.");
if (anchor == null)
throw new NullPointerException("anchor is null");
int xPos, yPos;
anchor.getLocationOnScreen(location);
final Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.getWidth(),
location[1] + anchor.getHeight());
rootView.measure(0, 0);
final int rootHeight = rootView.getMeasuredHeight();
final int rootWidth = rootView.getMeasuredWidth();
final int anchorCenterPosX = anchorRect.centerX();
//默认显示在上面
xPos = anchorCenterPosX - rootWidth / 2;
yPos = anchorRect.top - rootHeight - margin;
if (grivity == POPGriVity.TOP) {
xPos = anchorCenterPosX - rootWidth / 2;
yPos = anchorRect.top - rootHeight - margin;
} else if (grivity == POPGriVity.BOTTOM) {
xPos = anchorCenterPosX - rootWidth / 2;
yPos = anchorRect.bottom + margin;
} else if (grivity == POPGriVity.LEFT) {
yPos = anchorRect.centerY()- rootHeight / 2;
xPos = anchorRect.left - rootWidth - margin;
} else if (grivity == POPGriVity.RIGHT) {
yPos = anchorRect.centerY()- rootHeight / 2;
xPos = anchorRect.right + margin;
}
showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos);
}
}</span>