您的位置:首页 > 移动开发 > Android开发

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);
    }


结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: