在app中设置一个按钮按下按钮后可以出现一个不覆盖原来界面的小界面里面有另外三个按钮用kotlin语言编写
- 首先,在XML布局文件中添加一个Button和一个FrameLayout,用于放置小界面的容器:
<Button
android:id="@+id/show_popup_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup" />
<FrameLayout
android:id="@+id/popup_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
- 在Kotlin代码中,找到Button并为其添加点击事件处理程序,以便在点击时显示小界面:
val showPopupButton = findViewById<Button>(R.id.show_popup_button)
showPopupButton.setOnClickListener {
// Show popup here
}
- 接下来,创建一个新的布局文件来定义小界面的内容。例如,可以创建一个名为popup_layout.xml的文件,其中包含三个Button:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/popup_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />
<Button
android:id="@+id/popup_button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2" />
<Button
android:id="@+id/popup_button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3" />
</LinearLayout>
- 在Kotlin代码中,创建一个新的布局Inflater,并使用它将popup_layout.xml文件解析为一个View对象:
val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val popupView = inflater.inflate(R.layout.popup_layout, null)
- 创建一个新的PopupWindow对象,并为其设置内容视图:
val popupWindow = PopupWindow(popupView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
- 最后,将PopupWindow对象显示在屏幕上:
popupWindow.showAsDropDown(showPopupButton)
完整的代码如下:
val showPopupButton = findViewById<Button>(R.id.show_popup_button)
showPopupButton.setOnClickListener {
val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val popupView = inflater.inflate(R.layout.popup_layout, null)
val popupWindow = PopupWindow(popupView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
popupWindow.showAsDropDown(showPopupButton)
}
``
原文地址: https://www.cveoy.top/t/topic/cnre 著作权归作者所有。请勿转载和采集!