弹出框-----popupWindow
Android对话框的一种(阻塞线程所以这里不能做耗时操作),另外一种是AlertDialog(不阻塞线程)
popupWindow按照有无偏移分为有偏移无偏移按相对位置分可以分为相对某一控件相对父容器
方法如下
showAsDropDown(View ancher)相对于某个空间的位置(正左下方),无偏移
showAsDropDown(View anchor,int xoff,int yoff)相对与某个空间的位置,有偏移。
showAtLocation(View parent,int gravity,int x,int y)相对于父控件的位置(如Gravity.CENTER,正中,Gravity.BOTTOM,下方)也可以设置有无偏移
具体的实现步骤
在activity中创建一个popupWindow的对象window
参数一给popupwindow设置的布局(用布局加载器加载进来),参数二,三:布局的宽高 高一般设置为包裹内容
ViewGroup.LayoutParams.WRAP_CONTENT
popupWindow window=new popupWindow(View contentView,int width,int height);
window.setFocusable(true);
默认是false popupwindow没有获取焦点的能力 这里将其置为true让popupwindow具有获取焦点的
能力这样才能操作上面的输入框等
window.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_launcher));
设置popupwindow的背景因为是drawable类型无法直接放资源需要下面的方式来获取也可以直接创建一个
window.setAnimationStyle(R.style.popwin_anim_style);
给popupwindow设置动画(此动画需要在styles资源中要先定义好两个动画(一个打开一个收起)在放在资源文件里)
<style name="popwin_anim_style">
<item name="android:windowEnterAnimation">@anim/pop</item>
<item name="android:windowExitAnimation">@anim/out</item>
</style>
window.setshowAsDropDown(button);
设置显示的位置在某个控件的下方
public class MainActivity extends Activity {
public Button button;
public PopupWindow popupWindow;
View view;
LayoutInflater inflater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btn1);
button.setOnClickListener(l);
inflater = LayoutInflater.from(this);
}
OnClickListener l = new OnClickListener() {
@Override
public void onClick(View v) {
if (popupWindow == null) {
view = inflater.inflate(R.layout.popupwindows, null);
popupWindow = new PopupWindow(view, 200,
ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setFocusable(true);// 设置点击任意位置收回
popupWindow.setBackgroundDrawable(getResources().getDrawable(
R.drawable.ic_launcher));
popupWindow.setAnimationStyle(R.style.popwin_anim_style);
}
// popupWindow.showAsDropDown(button);//在谁的下面显示
View view2 = inflater.inflate(R.layout.activity_main, null);
if (popupWindow.isShowing()) {
popupWindow.dismiss();
}else{
popupWindow.showAtLocation(view2, Gravity.BOTTOM,-100, 30);
}
}
};
}
本文详细介绍了Android中对话框的一种实现方式——popupWindow的使用方法,包括其基本概念、具体实现步骤以及关键属性配置。通过实例展示了如何创建、配置并动态显示popupWindow,同时提供了popupWindow的关闭与位置调整方法。
995

被折叠的 条评论
为什么被折叠?



