android自定义PopupWindow,不显示内容

时间:2021-10-12 06:02:42
public class PopWindow extends PopupWindow {
private Context mContext;
private View mPopView;
private OnAnimationDismissListener mOnAnimationDismissListener;

public PopWindow(Context context, View contentView) {
super(contentView, LayoutParams.MATCH_PARENT, <span style="font-family: Arial, Helvetica, sans-serif;">contentView.getMeasuredHeight()</span><span style="font-family: Arial, Helvetica, sans-serif;">, true);</span>
Log.e("TAG", "" + contentView.getMeasuredHeight());

this.mContext = context;
this.mPopView = contentView;
init();
}

private void init() {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mPopView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
mPopView.setLayoutParams(lp);
setContentView(mPopView);
setBackgroundDrawable(new ColorDrawable(Color
.parseColor("#00000000")));
setFocusable(true);
setOutsideTouchable(true);
}

public void show(View anchor, int xoff, int yoff) {
showAsDropDown(anchor, xoff, yoff);
update();
Animation anim = AnimationUtils.loadAnimation(mContext, R.anim.down);
mPopView.startAnimation(anim);
}

@Override
public void dismiss() {
Animation anim = AnimationUtils.loadAnimation(mContext, R.anim.up);
anim.setAnimationListener(new SimpleAnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
if (null != mOnAnimationDismissListener)
mOnAnimationDismissListener.onStart();
}

@Override
public void onAnimationEnd(Animation animation) {
new Handler().post(new Runnable() {
@Override
public void run() {
PopWindow.super.dismiss();
}
});
}
});
mPopView.startAnimation(anim);
}

public void setOnAnimationDismissListener(
OnAnimationDismissListener onAnimationDismissListener) {
this.mOnAnimationDismissListener = onAnimationDismissListener;
}

public interface OnAnimationDismissListener {
public void onStart();
}
}



这里调用的在外部调用show()的时候发现,显示不了PopWindow,通过logcat发现这里的contentView.getMeasuredHeight()返回的是0。

所以这里就不能这样子使用了。改成如下方法即可:

public PopWindow(Context context, View contentView) {
super(contentView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
Log.e("TAG", "" + contentView.getMeasuredHeight());
//......
}


总结:很多时候涉及到宽高来设定View或者窗口大小的时候,都需要注意如果需要从其他的view获取这个大小,看看取得的值是否是0。

有时候需要借助addOnGlobalLayoutListener()方法,等布局大小等全部都已经确定好了在获取相应view的宽高。