項目中需要對toolbar右邊的menu操作,發(fā)現點擊的時候找不到menu中的view拉宗,在網上找了下資料才發(fā)現代赁,需要在onCreateOptionsMenu中添加 super.onCreateOptionsMenu(menu)缆镣,然后在onOptionsItemSelected 中通過findViewById就可以找到menu布局中的view了搓茬。
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="always"/>
menu中的布局app:showAsAction必須是always,要不然還是為null犹赖。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
View view = findViewById(R.id.action_settings);
//這里的view在添加super.onCreateOptionsMenu(menu);后不為null了
return true;
}
return super.onOptionsItemSelected(item);
}