Reputation: 225
I am not sure what I am doing wrong here but for some reason the Line R.id.action_search remains unresolved even though I have defined it in the menu/main.xml
here is the MainActivity.java
package com.example.myfirstapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
//... other methods above
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
//handle each number from the item in a case block
switch (item.getItemId())
{
case R.id.action_search: //error on this R.id call. Unresolved
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Here is the code in the main.xml file:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"
android:showAsAction="ifRoom" />"
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
</menu>
Is there anything that I did wrong? Is there a way that I am supposed to define my id's?
Upvotes: 1
Views: 7393
Reputation: 11
My SDK had me convert the switch/case structure to an if/else if/else one. It's weird that it worked for me after that.
int itemId = item.getItemId();
if (itemId == R.id.action_search) {
openSearch();
return true;
} else if (itemId == R.id.action_settings) {
openSettings();
return true;
} else {
return super.onOptionsItemSelected(item);
}
Upvotes: 1
Reputation: 6747
Whenever your generated R class isn't generated, it indicates that there's a problem with generating it due to some parsing issue from the XML resources. Check the error console in your IDE to figure out what's specifically wrong.
Common problems are:
strings.xml
, for instance you're
instead of you\'re
layout_width
or layout_height
tags in layout resourcesUpvotes: 0
Reputation: 5302
Add this in your code. Generally you should keep your menu related items in menu under res folder.
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);
// If it in menu folder then use R.menu.main and if it in layout then use R.menu.main
return true;
}
Upvotes: 0
Reputation: 887
You don't seem to be importing your project's R.java. Try that
Upvotes: 0