android popupwindow 屏幕居中,【android】让popupwindow显示在view的上方并与该view水平居中对齐...

本文介绍了如何在Android中使PopupWindow在点击按钮后居中显示,并且与按钮保持水平对齐。通过示例代码展示了具体的实现方法,包括设置PopupWindow的宽高、测量位置以及使用Gravity和getLocationOnScreen()方法来调整显示位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,废话少说,先上效果图:

0818b9ca8b590ca3270a3433284dd417.png

代码:

public class MainActivity extends Activity implements OnClickListener{

private Button showBtn1;

private Button showBtn2;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

showBtn1 = (Button) findViewById(R.id.showBtn1);

showBtn2 = (Button) findViewById(R.id.showBtn2);

showBtn1.setOnClickListener(this);

showBtn2.setOnClickListener(this);

}

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

View popupView = LayoutInflater.from(this).inflate(R.layout.popup, null);

PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT,

ViewGroup.LayoutParams.WRAP_CONTENT, true);

popupWindow.setBackgroundDrawable(new BitmapDrawable());

popupView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);

int popupWidth = popupView.getMeasuredWidth();

int popupHeight = popupView.getMeasuredHeight();

int[] location = new int[2];

switch (v.getId()) {

case R.id.showBtn1:

v.getLocationOnScreen(location);

popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0]+v.getWidth()/2)-popupWidth/2,

location[1]-popupHeight);

break;

case R.id.showBtn2:

v.getLocationOnScreen(location);

popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0]+v.getWidth()/2)-popupWidth/2,

location[1]-popupHeight);

break;

default:

break;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值