出现在控件下方的PopupWindow
这种方法可以自己设置出现的位置,主要是以出现在空间的下方为主;
布局都是简单布局,就不演示布局代码了;
效果图:
先看一下设置背景色的代码:
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:popupWindowStyle">@style/popBackground</item>
</style>
<style name="popBackground" parent="AppTheme">
<item name="android:popupBackground">#DAE0E0</item>
</style>
</resources>
*设置以下默认的背景颜色,如果不设置 默认是黑色半透明;*
java代码
public void myPop(){
View view = LayoutInflater.from(this).inflate(R.layout.my_pop, null);
lv = view.findViewById(R.id.lv);
String[] s = {"添加好友","添加群","扫一扫","面对面","我的钱包"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,s);
lv.setAdapter(adapter);
PopupWindow window = new PopupWindow(this);
window.setContentView(view);
window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
window.setWidth(300);
window.setOutsideTouchable(true);
window.showAsDropDown(img);
}
还有其他的显示方法 除了上面的显示在控件下方,还可以设置偏移量
另外一种,根据父控件设置位置:window.showAtLocation(view1, Gravity.BOTTOM,0,0);
第一个参数是布局,第二个参数是设置显示位置,后面两个参数是偏移量
出现的位置可以是中间,底部和顶端
Gravity.TOP//顶端
Gravity.BOTTOM//底部
Gravity.CENTER//中间
java代码
public void myPopupWindow(){
View view = LayoutInflater.from(this).inflate(R.layout.pop_me, null);
qx = view.findViewById(R.id.qx);
View view1 = LayoutInflater.from(this).inflate(R.layout.activity_day03, null);
final PopupWindow window = new PopupWindow(Activity_day03.this);
window.setContentView(view);
window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
window.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
window.setOutsideTouchable(true);
window.showAtLocation(view1, Gravity.BOTTOM,0,0);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.alpha = 0.5f;
getWindow().setAttributes(params);
window.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
WindowManager.LayoutParams params = getWindow().getAttributes();
params.alpha = 1.0f;
getWindow().setAttributes(params);
window.dismiss();
}
});
}
效果图如下:
设置位置不同出现的效果则不一样,也有可能因为模拟器的不同,会有不同效果,如果相对窗口中的按钮进行操作,去获取View然后获取控件即可,进行监听就OK了;