入门级测试Kotlin PopWindow弹窗代码
文件名称:MainActivity.Kt
package com.example.alert
import android.app.Dialog
import android.content.DialogInterface
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import android.widget.GridView
import android.widget.PopupWindow
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
class MainActivity : AppCompatActivity() {
private var btn : Button? = null
private var btnPopupWindow :Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//设定按钮
btn = findViewById<Button>(R.id.btnAlert)
btn?.setOnClickListener {
//告警窗口
val alertDialog = AlertDialog.Builder(this@MainActivity)
alertDialog.apply {
setTitle("Hello") //设置标题
setMessage("你说呢?")
setPositiveButton("确定",
DialogInterface.OnClickListener{ _, _ ->
Toast.makeText(this@MainActivity,"你点击了:确定",Toast.LENGTH_SHORT).show()
})
setNegativeButton("取消",
DialogInterface.OnClickListener { _, _ ->
Toast.makeText(this@MainActivity,"你点击了:取消",Toast.LENGTH_SHORT).show()
})
setIcon(R.drawable.ic_baseline_android_24)
show()
}
}
//弹窗部分开始
btnPopupWindow = findViewById<Button>(R.id.btnPopWindow)
btnPopupWindow?.setOnClickListener {
PopupWindow().apply {
//入口参数配置
contentView = layoutInflater.inflate(R.layout.popwindow_layout,null)
width = ViewGroup.LayoutParams.WRAP_CONTENT
height = ViewGroup.LayoutParams.WRAP_CONTENT
isFocusable = true
//设置按钮
val btnPopupWindow = contentView.findViewById<Button>(R.id.popBtn)
btnPopupWindow.setOnClickListener {
Toast.makeText(this@MainActivity,"退出弹窗!!",Toast.LENGTH_SHORT).show()
dismiss()
}
//显示在按钮的下方
showAsDropDown(it)
}
//这部分注释代码与上面效果一致,除了没添加按钮
// var popupWindow = PopupWindow(
// layoutInflater.inflate(R.layout.popwindow_layout,null),
// ViewGroup.LayoutParams.WRAP_CONTENT,
// ViewGroup.LayoutParams.WRAP_CONTENT,
// true
// )
//
//
// popupWindow.apply {
// showAsDropDown(it)
// }
}
}
}
文件名称:popwindow_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<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:text="你好,我是弹窗!!"
android:textSize="23sp"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/popBtn"
android:text="你好,我是弹窗按钮!!"
android:textSize="23sp"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
总结:使用Kotlin可以简化代码,代码量远比Java要跟小一些,使用内置函数apply灵活性强,代码更加容易看懂。