I know this has been covered开发者_如何学Python elsewhere, but I'm new to the Android platform and am having a hard time figuring out how to add basic menu options to my first app.
I have an options menu setup using
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
and
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menuPrefs" android:icon="@android:drawable/ic_menu_preferences" android:title="Settings"></item>
</menu>
Then within my main java class I have
@Override
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId()==R.id.menuPrefs) {
showPrefs();
}
private void showPrefs() {
Intent i = new Intent(this, Prefs.class);
startActivity(i);
}
And then in Prefs.java I have
public class Prefs extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Toast.makeText(getBaseContext(), "FNORD", Toast.LENGTH_LONG).show();
}
}
Now from this I would expect to see the Toast message "FNORD" when the menu option is pressed, however the application stops unexpectedly.
If I move the toast statement into the showPrefs() function in place of the startActivity call it works.
You forgot to call super.onCreate(Bundle savedInstanceState);
on Prefs' onCreate()
method.
You need to learn how to Debug in Eclipse and how to use the ADB and DDMS tools.
In order to get more details about an exception/force close you need to look for a view in Eclipse called Logcat(you will find in the DDMS perspective) there you will find a detailed traceback when/what and on what line is the issue.
For this you should read a complete article about Debugging in Android using Eclipse
(source: droidnova.com)
Solution was that I needed to add the Prefs.xml to the manifest.
精彩评论