Android中PopupWindow的使用

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>

Android中PopupWindow的使用_第1张图片

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

结果:
Android中PopupWindow的使用_第2张图片

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中PopupWindow的使用_第3张图片

你可能感兴趣的:(android,对话框)