728x90
반응형
[실습 7-2]의 컨텍스트 메뉴를 메뉴 XML 파일 없이 Kotlin 코드로만 완성하라.
MainActivity
package com.example.project7_2
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.*
import android.widget.Button
import android.widget.LinearLayout
class MainActivity : AppCompatActivity() {
lateinit var baseLayout : LinearLayout
lateinit var button1 : Button
lateinit var button2 : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "배경색 바꾸기(컨텍스트 메뉴)"
baseLayout = findViewById<LinearLayout>(R.id.baseLayout) as LinearLayout
button1 = findViewById<Button>(R.id.button1) as Button
registerForContextMenu(button1)
button2 = findViewById<Button>(R.id.button2) as Button
registerForContextMenu(button2)
}
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 // true 값을 반환합니다.
}
2 -> { // 배경색 (초록) 메뉴가 선택되었을 경우
baseLayout.setBackgroundColor(Color.GREEN)
return true // true 값을 반환합니다.
}
3 -> { // 배경색 (파랑) 메뉴가 선택되었을 경우
baseLayout.setBackgroundColor(Color.BLUE)
return true // true 값을 반환합니다.
}
4 -> { // 버튼 45도 회전 메뉴가 선택되었을 경우
button1.rotation = 45f
button2.rotation = 45f
return true // true 값을 반환합니다.
}
5 -> { // 버튼 2배 확대 메뉴가 선택되었을 경우
button1.scaleX = 2f
button1.scaleY = 2f
button2.scaleX = 2f
button2.scaleY = 2f
return true // true 값을 반환합니다.
}
else -> return super.onOptionsItemSelected(item) // 다른 경우에는 super 메소드를 호출합니다.
}
}
}
728x90
반응형
'Kotlin' 카테고리의 다른 글
[Kotlin을 활용한 안드로이드 프로그래밍] 9-2 직접 풀기 (0) | 2023.05.27 |
---|---|
[Kotlin을 활용한 안드로이드 프로그래밍] 시스템 폴더/파일목록 (0) | 2023.05.22 |
코틀린 에뮬레이터 or 디바이스 내에 폴더 생성 및 삭제 (1) | 2023.05.22 |
코틀린 디바이스에서 파일 읽어서 표시하기 (0) | 2023.05.21 |
[Kotlin을 활용한 안드로이드 프로그래밍] 직접 풀어보기 7-1 (0) | 2023.05.15 |