在进行android开发时,有时需要实现这样一个功能,在点击某个按钮之后弹出一个窗口,上面放置着一些控件,再次点击按钮之后,弹窗消失,下面是使用PopUpWindow的一些实现:
一、创建一个布局文件activity_popupwindow.xml,并放置所需要的控件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#66000000">
<!--放置所需要的控件 -->
</RelativeLayout>
二、编写窗口显示函数,具体的细节在注释中给出:
PopupWindow popupWindow = null;
//一个自定义的布局,作为显示的内容
private void showPopupWindow(View view){
//初始化布局activity_popupwindow.xml
View contentView = getLayoutInflater().inflate(R.layout.activity_popupwindow, null);
//对布局里面的控件进行初始化并进行相应的操作
//初始化PopupWindow
popupWindow = new PopupWindow(contentView,
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT
,true);
popupWindow.setTouchable(true);
popupWindow.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Toast.makeText(VirtualStickActivity.this,"已加载",Toast.LENGTH_SHORT).show();
return false;
//这里如果返回true的话,touch事件将会被拦截
//拦截后 PopupWindow的onTouchEvent不被调用,这样点击外部区域无法dismiss
}
})
//设置好参数之后再show
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.showAsDropDown(view);
}
三、在主布局中添加按钮,进行初始化并调用OnClick事件:
showBtn = (Button)findViewById(R.id.show);
showBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//调用第二步编写的窗口显示函数
showPopupWindow(v);
}
});
最后,提供一个PopupWindow的布局文件:
代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#66000000">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:background="@drawable/pop_bg"
android:layout_height="wrap_content"
android:paddingBottom="2dp">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@drawable/list_line"/>
</LinearLayout>
</RelativeLayout>
图片: