Android Application
Kotlin 메뉴(Menu) : 배경색 변경 앱 - Kotlin 코드만 이용한 옵션 메뉴
작성자 임베디드코리아
작성일23-11-16 11:47
조회1,395회
댓글0건
Kotlin 메뉴(Menu) : 배경색 변경 앱 - Kotlin 코드만 이용한 옵션 메뉴
-------------------------------------------------------------------------------------
activity_main.xml
-------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/baseLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="오른쪽 위 메뉴 버튼을 누르세요"
android:textSize="20dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="이건 버튼" />
</LinearLayout>
------------------------------------------------------------------------------------
MainActivity.kt
------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
lateinit var baseLayout : LinearLayout
lateinit var button1 : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "배경색 바꾸기"
baseLayout = findViewById<LinearLayout>(R.id.baseLayout)
button1 = findViewById<Button>(R.id.button1)
}
override fun onCreateOptionsMenu(menu: Menu?) : Boolean {
super.onCreateOptionsMenu(menu)
menu!!.add(0, 1, 0, "배경색 (빨강)")
menu!!.add(0, 2, 0, "배경색 (초록)")
menu!!.add(0, 3, 0, "배경색 (파랑)")
var sMenu : SubMenu = menu.addSubMenu("버튼 변경 >>")
sMenu.add(0, 4, 0, "버튼 45도 회전")
sMenu.add(0, 5, 0, "버튼 2배 확대")
return true
}
override fun onOptionsItemSelected(item: MenuItem) : Boolean {
when (item.itemId) {
1-> {
baseLayout.setBackgroundColor(Color.RED)
return true
}
2 -> {
baseLayout.setBackgroundColor(Color.GREEN)
return true
}
3 -> {
baseLayout.setBackgroundColor(Color.BLUE)
return true
}
4 -> {
button1.rotation = 45f
return true
}
5 -> {
button1.scaleX = 2f
return true
}
}
return false
}
}
-------------------------------------------------------------------------------------
***** themes.xml **********
-------------------------------------------------------------------------------------
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Base.Theme.MenuOptionmenu" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<item name="colorPrimary">#4255B3</item>
<item name="colorPrimaryDark">#FF9800</item>
</style>
<style name="Theme.MenuOptionmenu" parent="Base.Theme.MenuOptionmenu" />
</resources>