1.創建Menu選單
右鍵 res > New > Android Resource Directory > Resource type 選擇 menu
右鍵 menu > New > Menu Resource File
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/developer" android:title="開發" app:showAsAction="ifRoom"/>
<item android:id="@+id/setting" android:title="設定" app:showAsAction="ifRoom"/>
<item android:id="@+id/save" android:title="保存"/>
<item android:title="更多操作">
<menu>
<item android:id="@+id/edit" android:title="編輯" android:icon="@mipmap/ic_launcher"/>
<item android:id="@+id/share" android:title="分享"/>
</menu>
</item>
</menu>
1. android:id: 唯一標示
2. android:icon:圖示
3. android:title:標題
4. android:showAsAction:顯示方式
- always:永遠顯示在menu外
- ifRoom:有空間會顯示在menu外,否則到menu中
- withText:只會顯示標題
- never:永遠顯示在menu中
2.Options Menu
//顯示menu
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.option, menu)
return super.onCreateOptionsMenu(menu)
}
//menu監聽
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.developer -> {
Toast.makeText(this, "開發", Toast.LENGTH_SHORT).show()
}
R.id.setting -> {
Toast.makeText(this, "設定", Toast.LENGTH_SHORT).show()
}
R.id.save -> {
Toast.makeText(this, "保存", Toast.LENGTH_SHORT).show()
}
R.id.edit -> {
Toast.makeText(this, "編輯", Toast.LENGTH_SHORT).show()
}
R.id.share -> {
Toast.makeText(this, "分享", Toast.LENGTH_SHORT).show()
}
}
return super.onOptionsItemSelected(item)
}
3.Context Menu
//註冊長按點擊顯示menu
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
registerForContextMenu(findViewById(R.id.contextMenu))
}
//menu監聽
override fun onContextItemSelected(item: MenuItem): Boolean {
Toast.makeText(this, "您選擇的是" + item.title, Toast.LENGTH_SHORT).show();
return super.onContextItemSelected(item)
}
//顯示menu
override fun onCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) {
menuInflater.inflate(R.menu.option, menu)
super.onCreateContextMenu(menu, v, menuInfo)
}
4.Popup Menu
fun popMenu(view: View) {
val menu = PopupMenu(this , view)
menu.menuInflater.inflate(R.menu.option, menu.menu)
//menu監聽
menu.setOnMenuItemClickListener {
Toast.makeText(applicationContext, it.title, Toast.LENGTH_SHORT).show()
super.onOptionsItemSelected(it);
}
//顯示menu
menu.show()
}