Android中自定义PoupWindow的实现

需求,通过点击悬浮按钮,弹出一个含有两个按钮的框,供用户进行操作。

首先自定义一个布局文件service_layout.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/paizhao" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/paizhao" />
</LinearLayout>

效果如下:


然后在Activity中加入这个弹窗,代码如下:

private FloatingActionButton floatingActionButton=null;

private WebView webView=null;
private View serviceView=null;
private PopupWindow popupWindow=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_home); 
	//初始化悬浮按钮
	floatingActionButton=(FloatingActionButton)findViewById(R.id.fab);
	//设置弹出框
	serviceView= LayoutInflater.from(HomeActivity.this).inflate(R.layout.service_popu,null);
	popupWindow=new PopupWindow();
	popupWindow.setContentView(serviceView);//设置要弹出的界面
	popupWindow.setWidth(DrawerLayout.LayoutParams.WRAP_CONTENT);//设置弹出框的尺寸为适应控件
	popupWindow.setHeight(DrawerLayout.LayoutParams.WRAP_CONTENT);
	popupWindow.setFocusable(true);
	popupWindow.setAnimationStyle(R.style.PopupServiceAnimation);//设置弹出的动作,要不然太强硬
	popupWindow.setFocusable(true);
	popupWindow.setTouchable(true);

	floatingActionButton.setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			//获取悬浮窗的坐标位置
			int[] location = new int[2];
			floatingActionButton.getLocationOnScreen(location);
			int x = location[0];
			int y = location[1];
			popupWindow.showAtLocation(floatingActionButton, Gravity.NO_GRAVITY,x,y-500);
		}
	});
}
代码可能不能直接执行,仅供参考,最后实现的效果如下:




猜你喜欢

转载自blog.csdn.net/dzjin1234/article/details/78984004
今日推荐