Android Application
Kotlin 메뉴(Menu) : 컨텍스트 메뉴(ContextMenu)
작성자 임베디드코리아
작성일23-11-16 11:51
조회1,212회
댓글0건
Kotlin 메뉴(Menu) : 컨텍스트 메뉴(ContextMenu)
-------------------------------------------------------------------------------------
activity_main.xml
-------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_menu1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="context menu" />
</LinearLayout>
------------------------------------------------------------------------------------
MainActivity.kt
------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// setContentView(R.layout.activity_main)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
registerForContextMenu(binding.btnMenu1) // 컨텍스트 메뉴에 등록
}
// 컨텍스트 메뉴로 등록한 view 롱클릭 시 호출되는 메소드
override fun onCreateContextMenu(
menu: ContextMenu?,
v: View?,
menuInfo: ContextMenu.ContextMenuInfo?
) {
super.onCreateContextMenu(menu, v, menuInfo)
when (v?.id) { // 여러 버튼을 등록했을 경우 뷰 아이디에 따라 메뉴 inflate
R.id.btn_menu1 -> menuInflater.inflate(R.menu.context_menu, menu)
}
}
// 컨텍스트 메뉴 아이템 선택 시 호출되는 메소드
override fun onContextItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.Context01 -> Toast.makeText(this, "첫번째 아이템 클릭함", Toast.LENGTH_LONG).show()
R.id.Context02 -> Toast.makeText(this, "두번째 아이템 클릭함", Toast.LENGTH_LONG).show()
else -> Toast.makeText(this, item.title, Toast.LENGTH_LONG).show()
}
return super.onContextItemSelected(item)
}
}
-------------------------------------------------------------------------------------
***** context_menu.xml * ******
menu 폴더 만들기 --> New ---> Android Resource Directory
context_menu.xml 만들기 --> New ---> Menu Resource File
-------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/Context01"
android:title="Context Menu 1" />
<item
android:id="@+id/Context02"
android:title="Context Menu 2" />
<item
android:id="@+id/Context03"
android:title="Context Menu 3" />
<item
android:id="@+id/Context04"
android:title="Context Menu 4" />
</menu>