PopupWindow 简单封装
2021-04-06 本文已影响0人
面向星辰大海的程序员
public abstract class CommonPopWindow extends PopupWindow implements OnClickListener, PopupWindow.OnDismissListener {
private int layout;
private Context context;
private View contentView;
private View rotateView;
}
public CommonPopWindow(Context context, int layout, int width, int height) {
this.context = context;
this.layout = layout;
this.setWidth(width);
this.setHeight(height);
init();
}
public CommonPopWindow(Context context, int layout) {
this.context = context;
this.layout = layout;
this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
init();
}
private void init() {
this.setFocusable(true);
// 设置PopupWindow的背景
this.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// 设置PopupWindow是否能响应外部点击事件
this.setOutsideTouchable(true);
// 设置PopupWindow是否能响应点击事件
this.setTouchable(true);
// 每个方法的作用都写在注解里了,相信大家都能看懂。不过这里要注意这两行:
// window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// window.setOutsideTouchable(true);
// 只有同时设置PopupWindow的背景和可以响应外部点击事件,它才能“真正”响应外部点击事件。也就是说,当你点击PopupWindow的外部或者按下“Back”键时,PopupWindow才会消失。
contentView = LayoutInflater.from(context).inflate(layout, null, false);
this.setContentView(contentView);
convert(contentView);
}
public abstract void convert(View popView);
public void addListenerId(int... id) {
for (int i = 0; i < id.length; i++) {
contentView.findViewById(id[i]).setOnClickListener(this);
}
}
public void onMyClickListener(View v) {
}
@Override
public void onClick(View v) {
onMyClickListener(v);
}
public void startRodate(int id) {
rotateView = contentView.findViewById(id);
Animation rotateAnimation = AnimationUtils.loadAnimation(context, R.anim.loading_rotate);
LinearInterpolator linearInterpolator = new LinearInterpolator();
rotateAnimation.setInterpolator(linearInterpolator);
rotateView.startAnimation(rotateAnimation);
}
public void showOnParentCenter(View parentView) {
showAtLocation(parentView, Gravity.CENTER, 0, 0);
}