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

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



代码:

[java]  view plain copy
  1. public class MainActivity extends Activity implements OnClickListener{  
  2.   
  3.     private Button showBtn1;  
  4.     private Button showBtn2;  
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.activity_main);  
  9.   
  10.         showBtn1 = (Button) findViewById(R.id.showBtn1);  
  11.         showBtn2 = (Button) findViewById(R.id.showBtn2);  
  12.         showBtn1.setOnClickListener(this);  
  13.         showBtn2.setOnClickListener(this);  
  14.     }  
  15.   
  16.     @Override  
  17.     public void onClick(View v) {  
  18.         // TODO Auto-generated method stub  
  19.         View popupView = LayoutInflater.from(this).inflate(R.layout.popup, null);  
  20.         PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT,   
  21.                 ViewGroup.LayoutParams.WRAP_CONTENT, true);  
  22.         popupWindow.setBackgroundDrawable(new BitmapDrawable());  
  23.         popupView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);  
  24.         int popupWidth = popupView.getMeasuredWidth();  
  25.         int popupHeight =  popupView.getMeasuredHeight();  
  26.         int[] location = new int[2];  
  27.         switch (v.getId()) {  
  28.         case R.id.showBtn1:  
  29.             v.getLocationOnScreen(location);  
  30.             popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0]+v.getWidth()/2)-popupWidth/2,  
  31.                     location[1]-popupHeight);  
  32.             break;  
  33.         case R.id.showBtn2:  
  34.             v.getLocationOnScreen(location);  
  35.             popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0]+v.getWidth()/2)-popupWidth/2,  
  36.                     location[1]-popupHeight);  
  37.             break;  
  38.   
  39.         default:  
  40.             break;  
  41.         }  
  42.     }  
  43. }  


Demo下载:http://download.csdn.net/detail/u011494050/7787359

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值