码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2014-08-20 00:02:04      阅读:312      评论:0      收藏:0      [点我收藏+]

标签:android

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

bubuko.com,布布扣


代码:

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;
		}
	}
}


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

【android】让popupwindow显示在view的上方并与该view水平居中对齐,布布扣,bubuko.com

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

标签:android

原文地址:http://blog.csdn.net/u011494050/article/details/38691475

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!