基于PopWindow实现的Android弹窗视图

手机上的软件有各种的广告弹窗和对应的点击实现跳转另外的窗口令人防不胜防,我接下来会实现简单的弹窗视图,具体的其他小功能可自行添加视图点击事件。

实现弹窗我们需要三个文件: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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值