现在,我正在研究android开发人员培训。在“添加动作按钮”中,我遇到了一些问题。
我编写了如下所示的xml代码,但在MainActivity.java
中,action_search
和action_settings
出现错误,编译器表示无法解析或无法解析字段。然后,我阅读了修复代码“在action_search
类型中创建字段id
”的建议。我已经编写了代码"@+id/action_search"
和"@+id/action_settings"
。为什么会出现此错误,请告诉我们!
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"
android:showAsAction="ifRoom" />
<!-- Settings, should always be in the overflow -->
<item android:id="@+id/action_settings"
android:title="@string/action_settings"
android:showAsAction="never" />
</menu>
编辑:按要求编写的代码
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}