手机上的软件有各种的广告弹窗和对应的点击实现跳转另外的窗口令人防不胜防,我接下来会实现简单的弹窗视图,具体的其他小功能可自行添加视图点击事件。
实现弹窗我们需要三个文件:MainActivity,activity_main.xml,popup_layout.xml(弹窗视图,可在内部修饰)。
首先我们在MainActivity使用一个按钮点击事件打开弹窗:
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
//
}
}
activity_main.xml只需要一个按钮布局就可以了:
<?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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
然后回到MainActivity加载弹窗视图,使用getLayoutInflater().inflate
方法将弹窗布局文件popup_layout
加载为一个View
对象,popupView
就是这个加载好的视图。:
View popupView = getLayoutInflater().inflate(R.layout.popup_layout, null);
然后调用imageView作为弹窗内的视图,由于popupView
是弹窗的根视图,不能直接通过findViewById
引用里面的视图,所以通过popupView.findViewById
方法获取弹窗内的视图引用。
!!!!!!!切记,如果要在弹窗里面添加视图如Textview,ImageView,所有的弹窗视图必须在这个点击事件里面添加,不然无法引用。
//由于弹窗里的视图不能直接通过fi