Android中PopupWindow的使用
2015-08-28 19:47
471 查看
PopupWindow简单使用
PopupWindow与AlertDialog都是属于一种对话框,不同的是AlertDialog位置比较固定,而PopupWindow位置不固定,比较随意。PopupWindow是以一种弹窗的形式呈现的。下面我们来看看PopupWindow的使用。1. 首先我们定义一个PopupWindow的布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/textview1" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="10dp" android:text="文本1"/> <TextView android:id="@+id/textview2" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="10dp" android:text="文本2"/> <TextView android:id="@+id/textview3" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="10dp" android:text="文本3"/> <TextView android:id="@+id/textview4" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="10dp" android:text="文本4"/> </LinearLayout>
2. 我们通过按钮的点击事件来弹出PopupWindow,我们定义一个弹出PopupWindow的方法,通过在点击事件中调用此方法。
private void showPopupWindow() { //定义了一个全局变量 private PopupWindow mPopupWindow; mPopupWindow = new PopupWindow(MainActivity.this); //获得PopupWindow的布局 View popupview = getLayoutInflater().inflate(R.layout.layout_popupwindow,null); //将布局添加到PopupWindow中 mPopupWindow.setContentView(popupview); //设置PopupWindow的宽和高 mPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT); mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); //设置点击PopupWindow外的其他地方退出PopupWindow。 mPopupWindow.setFocusable(false); mPopupWindow.setOutsideTouchable(true); //定义在button下展示PopupWindow mPopupWindow.showAsDropDown(mButtonPopupWindow); }
结果:
Back键返退出PopupWindow
有时候我们想通过Back键来退出PopupWindow对话框,但是当我们没有设置去点击的时候通常会退出当前的Activity,那么我们应该如何设置按Back键是返回PopupWindow对话框呢?
我们需要在Activity中重写方法onKeyDown()。
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ if(mPopupWindow!=null&&mPopupWindow.isShowing()){ mPopupWindow.dismiss(); return true; } } return super.onKeyDown(keyCode, event); }
结果:
相关文章推荐
- Android Studio配置debug下使用正式签名调试
- Android开发中ANR问题出现及解决
- 消息传递之:IOS NSNotificationCenter,Android EventBus;
- Android虚拟机无法正常工作几例及解决办法
- android移动开发环境搭建与配置
- Android-Activity的四状态、七生命周期、和四启动模式
- (七)android开发中两种方式监听短信的原理和实现
- Unexpected namespace prefix "xmlns" found for tag LinearLayout——android开发之xml布局文件
- Android核心服务解析篇(一)——下载Android源代码
- Android通过PHP连接MySQL数据库(插入)
- Attribute is missing the Android namespace prefix——android开发之xml布局文件
- Android应用程序用户界面(三)
- Android Studio 获取证书指纹SHA1
- Android GridView中设置了Button以后就不能响应OnItemClick()
- Android百度地图定位demo
- android ListView 左滑和IOS一样的效果
- 导入Github上Android studio 项目
- 来自官方的Android数据绑定(Data Binding)框架②
- android 友盟自动更新
- 在 Android studio 中 配置Gradle 做到 “根据命令行提示符生成指定versionCode, versionName,指定apk的打包输出路径”