项目中需要对toolbar右边的menu操作,发现点击的时候找不到menu中的view,在网上找了下资料才发现,需要在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);
}
网友评论