반응형
PopupMenu
설명
- 개발자가 원할 때 원하는 곳에 띄울 수 있는 메뉴
코드
res/layout/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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="click" />
</LinearLayout>
res/menu/popup_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu1"
android:title="메뉴1" />
<item
android:id="@+id/menu2"
android:title="메뉴2" />
<item
android:id="@+id/menu3"
android:title="메뉴3">
<menu>
<item
android:id="@+id/menu3_1"
android:title="메뉴3-1" />
<item
android:id="@+id/menu3_2"
android:title="메뉴3-2" />
</menu>
</item>
</menu>
MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val textView = findViewById<TextView>(R.id.textView)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
val popupMenu = PopupMenu(this, textView)
menuInflater.inflate(R.menu.popup_menu, popupMenu.menu)
popupMenu.setOnMenuItemClickListener(PopupListener())
popupMenu.show()
}
}
inner class PopupListener : PopupMenu.OnMenuItemClickListener {
override fun onMenuItemClick(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.menu1 -> Toast.makeText(baseContext, "메뉴1", Toast.LENGTH_SHORT).show()
R.id.menu2 -> Toast.makeText(baseContext, "메뉴2", Toast.LENGTH_SHORT).show()
R.id.menu3 -> Toast.makeText(baseContext, "메뉴3", Toast.LENGTH_SHORT).show()
R.id.menu3_1 -> Toast.makeText(baseContext, "메뉴3-1", Toast.LENGTH_SHORT).show()
R.id.menu3_2 -> Toast.makeText(baseContext, "메뉴3-2", Toast.LENGTH_SHORT).show()
}
return false
}
}
}
참고
반응형
'Development > Android' 카테고리의 다른 글
[Android] AlertDialog (0) | 2021.02.09 |
---|---|
[Android] ActionBar (0) | 2021.02.09 |
[Android] ContextMenu (0) | 2021.02.09 |
[Android] OptionMenu (0) | 2021.02.09 |
[Android] Activity (0) | 2021.02.09 |