Android Studio Kotlin: 创建向上展开的按钮菜单
Android Studio Kotlin: 创建向上展开的按钮菜单
本文介绍如何在 Android Studio 中使用 Kotlin 语言创建一个按钮,点击后从按钮处向上展开一个包含三个按钮的菜单,同时保持原有界面不被遮挡。
操作步骤
- 在布局文件中添加一个按钮和一个线性布局(用于放置三个按钮):
<Button
android:id="@+id/expand_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Expand" />
<LinearLayout
android:id="@+id/expansion_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 2" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 3" />
</LinearLayout>
- 在 Activity 中找到按钮和线性布局:
val expandButton = findViewById<Button>(R.id.expand_button)
val expansionLayout = findViewById<LinearLayout>(R.id.expansion_layout)
- 给按钮添加点击事件,当点击按钮时展开/收起线性布局:
expandButton.setOnClickListener {
if (expansionLayout.visibility == View.GONE) {
expansionLayout.visibility = View.VISIBLE
} else {
expansionLayout.visibility = View.GONE
}
}
完整代码
布局文件:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/expand_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Expand"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"/>
<LinearLayout
android:id="@+id/expansion_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone"
android:layout_below="@+id/expand_button"
android:layout_marginTop="16dp">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 2" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 3" />
</LinearLayout>
</RelativeLayout>
Activity 代码:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val expandButton = findViewById<Button>(R.id.expand_button)
val expansionLayout = findViewById<LinearLayout>(R.id.expansion_layout)
expandButton.setOnClickListener {
if (expansionLayout.visibility == View.GONE) {
expansionLayout.visibility = View.VISIBLE
} else {
expansionLayout.visibility = View.GONE
}
}
}
}
总结
通过以上步骤,您就可以在 Android Studio 中使用 Kotlin 语言创建一个简单的向上展开按钮菜单,并通过点击按钮来控制菜单的展开和收起。您也可以根据需要对代码进行调整,以实现更多功能。
原文地址: https://www.cveoy.top/t/topic/nyIO 著作权归作者所有。请勿转载和采集!