[英]The method onOptionsItemSelected(MenuItem) is undefined for the type FragmentPagerAdapter
[英]Android - MenuItem onOptionsItemSelected method not working but returning no errors
我是相对较新的android开发人员,一直在尝试了解MenuItem,但并没有取得太大的成功。 单击菜单项时,我无法调用方法。 这是我的代码:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
String selectedMenuIdString = (String) item.getTitleCondensed();
if (selectedMenuIdString.equals("about")) {
doThis(item);
return true;
}
return true;
}
public void doThis(MenuItem item) {
Toast.makeText(this, "Hello World", Toast.LENGTH_LONG).show();
}
几天前它能工作一次,但现在不行了,我也不知道为什么。 有人可以帮忙吗?
<item
android:id="@+id/search"
android:orderInCategory="100"
android:title="@string/search"
android:titleCondensed="search"
/>
<item
android:id="@+id/products"
android:orderInCategory="100"
android:title="@string/products"/>
<item
android:id="@+id/contact_us"
android:orderInCategory="100"
android:title="@string/contactus"/>
<item
android:id="@+id/about"
android:orderInCategory="100"
android:title="@string/about"/>
和我的弦:
<string name="search">Search</string>
<string name="products">Products</string>
<string name="contactus">Contact Us</string>
<string name="about">About</string>
用这种方式做,要容易得多:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getId(); // Retrieve the id of the selected menu item
switch(id) {
case R.id.about: // "@+id/about" is the id of your menu item (menu layout)
doThis(item);
return true;
break;
case ...
}
return super.onOptionsItemSelected(item);
}
没有听众,没有额外的复杂性。
总是比较项目ID,而不是标题或其他内容,例如在另一个答案中。
另一很好的方式做到这一点:尝试通过处理点击事件OnMenuItemClickListener
,在onPrepareOptionsMenu功能。 下面的示例代码:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem prefs = menu.findItem(R.id.prefs); // your item identifier
prefs.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
doThis();
return false;
}
});
}
你说
String selectedMenuIdString = (String) item.getTitleCondensed();
if (selectedMenuIdString.equals("about")) {
而且About菜单项在这里似乎没有condensedTitle
<item
android:id="@+id/about"
android:orderInCategory="100"
android:title="@string/about"/>
因此,像下面这样修改您的代码:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.about:{
//do something here
return true;
break;
}
case R.id.search:{
//do something here
return true;
break;
}
case R.id.contact_us:{
//do something here
return true;
break;
}
case R.id.products:{
//do something here
return true;
break;
}
}
return super.onOptionsItemSelected(item);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.