android popupwindow 指定位置,Android中PopupWindow显示在指定位置

Android中PopupWindow位置的确定一般通过showAsDropDown函数来实现,该函数有两个重载函数,分别定义如下:public void showAsDropDown(View anchor) {

showAsDropDown(anchor, 0, 0);

}

public void showAsDropDown(View anchor, int xoff, int yoff) {

if (isShowing() || mContentView == null) {

return;

}

registerForScrollChanged(anchor, xoff, yoff);

mIsShowing = true;

mIsDropdown = true;

WindowManager.LayoutParams p = createPopupLayout(anchor.getWindowToken());

preparePopup(p);

updateAboveAnchor(findDropDownPosition(anchor, p, xoff, yoff));

if (mHeightMode < 0) p.height = mLastHeight = mHeightMode;

if (mWidthMode < 0) p.width = mLastWidth = mWidthMode;

p.windowAnimations = computeAnimationResource();

invokePopup(p);

}

也就是说,调用第一个函数时,x和y坐标偏移量默认是0,此时PopupWindow显示的结果如下中图所示。而要实现PopupWindow显示在wenwen的正下方时,就需要程序员自己进行坐标偏移量的计算,下右图所示,当点击wenwen时,PopupWindow显示在正下方,这正是我们所需要的,对称是一种美啊。

e09b1e0d3215b6a70f7166acbc9007f5.png

386430916a3fbf943c98b6ef76f3c53f.png

代码实现的关键是点击wenwen后的响应函数,此处直接上代码,不废话了:public void onClick(View v) {

LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

ViewGroup menuView = (ViewGroup) mLayoutInflater.inflate(

R.layout.tips, null, true);

pw = new PopupWindow(menuView, LayoutParams.WRAP_CONTENT,

LayoutParams.WRAP_CONTENT, true);

// 设置点击返回键使其消失,且不影响背景,此时setOutsideTouchable函数即使设置为false

// 点击PopupWindow 外的屏幕,PopupWindow依然会消失;相反,如果不设置BackgroundDrawable

// 则点击返回键PopupWindow不会消失,同时,即时setOutsideTouchable设置为true

// 点击PopupWindow 外的屏幕,PopupWindow依然不会消失

pw.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

pw.setOutsideTouchable(false); // 设置是否允许在外点击使其消失,到底有用没?

pw.setAnimationStyle(R.style.PopupAnimation); // 设置动画

// 计算x轴方向的偏移量,使得PopupWindow在Title的正下方显示,此处的单位是pixels

int xoffInPixels = ScreenTools.getInstance(PopDemoActivity.this).getWidth() / 2 - titleName.getWidth() / 2;

// 将pixels转为dip

int xoffInDip = ScreenTools.getInstance(PopDemoActivity.this).px2dip(xoffInPixels);

pw.showAsDropDown(titleName, -xoffInDip, 0);

//pw.showAsDropDown(titleName);

pw.update();

TextView tv = (TextView) menuView.findViewById(R.id.tips_ok);

tv.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

pw.dismiss();

}

});

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值