Android 开发中是使用 Popwindow
学习自:百度
Overview
今天闲着没事干,搜索了一波Android弹窗的使用,然后给我推送了一条Android中使用Popwindow的使用方法。我看了下效果,正是我说需要的。然后我就学习了一下.但是在开发的过程不是很顺利,我前面的一直在崩溃,闪退。但是现在终于到搞定了。
如何使用Popwindow
首先我们需要知道的是,我们的Popwindow
不是一个控件, 他就类似AlertDialog
。
接着我们看一下我们需要显示的文本的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@color/MainColor"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World Hello Android"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
这样我们的布局文件就完成了,接着让我看一下,怎样去使用我们的Popwindow
.
PopupWindow popupWindow;
void InitPOP() {
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.my_information, null);
if (popupWindow == null) {
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
popupWindow.setOutsideTouchable(true);
popupWindow.setHeight(400);
popupWindow.setTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
}
view.setOnClickListener(v -> {
popupWindow.dismiss();
});
if (popupWindow.isShowing()) {
popupWindow.dismiss();
} else
popupWindow.showAtLocation(LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null), Gravity.BOTTOM, 0, 0);
}
这样我们的Popwindow就创建完成了,这里我需要他显示的是从窗体的底部显示出来。而是随便他,所以我在显示的地方添加了从底部显示。
然后就是我们在使用 Popwindow的时候,我们我们经常会去设置两个属性:
popupWindow.setTouchable(true);
popupWindow.setFocusable(true);
这样我们的Popwindow 就设置完成.
还是很简单。