gpt4 book ai didi

java - Android - MenuItem onOptionsItemSelected 方法不起作用但未返回任何错误

转载 作者:行者123 更新时间:2023-11-29 06:56:06 25 4
gpt4 key购买 nike

我是 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);
}

没有听众,没有额外的复杂性。

关于java - Android - MenuItem onOptionsItemSelected 方法不起作用但未返回任何错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33845325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com