![](/img/trans.png)
[英]OnCreateOptions it is called but OnOptionsItemSelected it is not called
[英]onOptionsItemSelected not called
我的操作欄中有一個菜單項列表。 每次單擊項目都應觸發不同的方法。 但是永遠不會調用 onOptionsItemSelected。
這是在 MainActivity 中定義操作欄的方式:
public class MainActivity extends AppCompatActivity {
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings_1) {
//do something
return true;
} else if (id == R.id.action_settings_2) {
//do something
return true;
} else if (id == R.id.action_settings_1) {
//do something
return true;
}
return super.onOptionsItemSelected(item);
}
...
}
在您的onCreateOptionsMenu
,返回 true 而不是調用 super。 那應該這樣做
只需進行如下更改:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
在 onCreate() 中,調用 setSupportActionbar(),像這樣
toolbar = (Toolbar)findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
如果在 XML 中使用menu
屬性,也可能會發生此問題:
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
app:menu="@menu/your_menu"
app:navigationIcon="@drawable/..."
app:title="@string/..." />
所以app:menu="@menu/your_menu"
不適用於重寫的片段方法onOptionsItemSelected
。 菜單項單擊偵聽器必須設置為Toolbar
private fun setMenuClickListener(toolbar: MaterialToolbar) = with(toolbar) {
setOnMenuItemClickListener { menuItem ->
if (menuItem.itemId == R.id.yourId) {
//do something
return@setOnMenuItemClickListener true
}
//this is a lambda so it can be just false,
//added return to make it explicit
return@setOnMenuItemClickListener false
}
}
所以我們正在尋找的是來自MaterialToolbar
的setOnMenuItemClickListener
試試這個:
而不是實施
@Override
public boolean onCreateOptionsMenu
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.