Android Studio Kotlin 实现向上延伸菜单按钮 - 无遮挡界面
Android Studio Kotlin 实现向上延伸菜单按钮 - 无遮挡界面
本文将使用 Kotlin 在最新版 Android Studio 中实现一个向上延伸菜单按钮。点击该按钮后,从按钮位置向上弹出包含三个按钮的菜单,同时保持原有界面不被遮挡。
1. 布局文件
在布局文件中添加一个按钮和一个 LinearLayout(作为菜单容器):
<Button
android:id="@+id/menuButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Menu" />
<LinearLayout
android:id="@+id/menuContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone" >
<Button
android:id="@+id/menuItem1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Menu Item 1" />
<Button
android:id="@+id/menuItem2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Menu Item 2" />
<Button
android:id="@+id/menuItem3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Menu Item 3" />
</LinearLayout>
2. Activity 代码
在 Activity 中获取按钮和菜单容器的引用,并为按钮添加点击事件:
val menuButton = findViewById<Button>(R.id.menuButton)
val menuContainer = findViewById<LinearLayout>(R.id.menuContainer)
menuButton.setOnClickListener {
if (menuContainer.visibility == View.GONE) {
menuContainer.visibility = View.VISIBLE
} else {
menuContainer.visibility = View.GONE
}
}
3. 运行程序
运行程序,点击按钮可以展开和收起菜单。
注意:
- 在本例中,菜单容器默认设置为不可见(visibility 属性为 gone),点击按钮时根据当前状态切换可见性。
- 如果需要实现更复杂的动画效果,可以使用属性动画等技术实现。
原文地址: https://www.cveoy.top/t/topic/nyff 著作权归作者所有。请勿转载和采集!