android popupwindow 模拟新浪、腾讯title弹框效果

     首先在上节中是使用dialog 实现的,(点击连接),现在我就讲些popupwindow 的实现,这个相对dialog比较简单,因为不用自定义dialog.

     实现代码很简单如下:

    代码片段:

     

public void showPopupWindow(int x, int y) {
		layout = (LinearLayout) LayoutInflater.from(MainActivity.this).inflate(
				R.layout.dialog, null);
		listView = (ListView) layout.findViewById(R.id.lv_dialog);
		listView.setAdapter(new ArrayAdapter<String>(MainActivity.this,
				R.layout.text, R.id.tv_text, title));

		popupWindow = new PopupWindow(MainActivity.this);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow
				.setWidth(getWindowManager().getDefaultDisplay().getWidth() / 2);
		popupWindow.setHeight(300);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		popupWindow.setContentView(layout);
		// showAsDropDown会把里面的view作为参照物,所以要那满屏幕parent
		// popupWindow.showAsDropDown(findViewById(R.id.tv_title), x, 10);
		popupWindow.showAtLocation(findViewById(R.id.main), Gravity.LEFT
				| Gravity.TOP, x, y);//需要指定Gravity,默认情况是center.

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				button.setText(title[arg2]);
				popupWindow.dismiss();
				popupWindow = null;
			}
		});
	}
   
button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				button.getTop();
				int y = button.getBottom() * 3 / 2;
				int x = getWindowManager().getDefaultDisplay().getWidth() / 4;

				showPopupWindow(x, y);
			}
		});


     


样子我就不贴了,和前面一章dialog显示的一样.

在这里遇到个小问题:int y = button.getBottom() * 3 / 2;这里获取的y坐标应该是 button.getBottom();可是这样写popupwindow就显示位置不对了,在button中间,不知道为什么。

   如果知道为什么了通知我一下,共同学习嘛,先谢谢了。

    

/*****************************纠正错误**********************************************************/ 

 首先上面int y = button.getBottom() * 3 / 2; 这个是错误的,只是偶尔符合了,实际上我少加了18像素.因为少加了一个状态栏 的高度

 正确写法:

 

	Rect frame = new Rect();
				getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
				state_heght = frame.top;// 状态栏的高度

				int y = button.getBottom()+state_heght ;
				int x = getWindowManager().getDefaultDisplay().getWidth()/4;

				showPopupWindow(x, y);

我们看一张图:

                 

         取消状态栏                                     没有加状态栏高度                            加状态栏高度

      

     其实popupwindow用起来比Dialog 方便,因为dialog一切都需要你自己来实现,而popupwindow帮我们实现了很多,我认为在使用的时候关键我们要看清参数:

       popupWindow.showAtLocation(parent, gravity, x, y);

        parent这个是一个父view试图,

       gravity  这个默认是居中,我们要指定显示方式:Gravity.LEFT
| Gravity.TOP

       最后两个参数就是显示的坐标位置,这样就可以根据需求自己定位显示位置了.

       好了,讲的不是很详细,不过之前那个问题解决了,以后在深究吧。



  源码下载 

     

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值