Reputation: 3587
I have a SettingsActivity
that should have an up button linking back to MainActivity
. The button appears, but doesn't do anything when clicked. The back button works fine.
AndroidManifest.xml
:
<activity
android:name=".SettingsActivity"
android:label="@string/title_activity_settings"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myapp.MainActivity" />
</activity>
I tried adding an action to onOptionsItemSelected
for R.id.home
with no luck. I also tried adding getActionBar().setDisplayHomeAsUpEnabled(true);
to onCreate()
, but it crashes the app with the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)'
Upvotes: 4
Views: 689
Reputation: 496
I suppose your code base was generated by Android Studio because I met the same problem. You can add the following code into your SettingsActivity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish(); // or go to another activity
return true;
}
return super.onOptionsItemSelected(item);
}
This will make sure the up button works.
Upvotes: 5