[英]What is the best (most efficient or conventional) way to control “MenuItem”s in Android's “ActionBar”?
When controlling a MenuItem, I have been doing this: 当控制MenuItem时,我一直在这样做:
Menu menu;
(...)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
this.menu = menu;
return true;
}
(...)
public void handleSearch(View view) {
Button button = (Button) view;
if(menu.findItem(R.id.action_search).isVisible()) {
button.setText(R.string.button_search_show);
menu.findItem(R.id.action_search).setVisible(false);
} else {
button.setText(R.string.button_search_hide);
menu.findItem(R.id.action_search).setVisible(true);
}
}
"this" being referencing the menu created in onCreateOptionsMenu with a Menu that any method in the class can use. “ this”通过类中任何方法都可以使用的Menu引用在onCreateOptionsMenu中创建的菜单。 The handleSearch method controls MenuItems by using findItem twice.
handleSearch方法通过两次使用findItem来控制MenuItems。 This doesn't feel very conventional or efficient (a very scientific observation, I might add).
这并不十分传统或有效(我可能会补充说,这是非常科学的观察)。 Is there a more conventional or efficient way to do this?
有更常规或有效的方法来做到这一点吗?
您可以将MenuItem保存在变量中,而不必两次使用findItem。
MenuItem myMenuitem = menu.findItem(R.id.action_search);
There is a method that handles actionBar's menu itself. 有一种方法可以处理actionBar的菜单本身。
Try this: 尝试这个:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
return (true);
case R.id.menu_home:
Intent i = new Intent(this, HomeActivity.class);
startActivity(i);
return (true);
}
return (super.onOptionsItemSelected(item));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.