Use onOptionsItemSelected to move up from PreferenceActivity with PreferenceFragments
I’m having trouble using onOptionsItemSelected
with Android Studio’s default Setup Activity (extending AppCompatPreferenceActivity
). An important part of the activity is:
public class SettingsActivity extends AppCompatPreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class GeneralPreferenceFragment extends PreferenceFragment {
// [...]
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android. R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
two more fragments
}
This is great for fragments — onOptionsItemSelected
@Override
works great, going back to SettingsActivity, but I want
SettingsActivity
When using the up button, returns control to its parent activity.
I read the documentation and I get it
Although your fragment receives an on-item-selected callback for each menu item it adds, the activity is first to receive the respective callback when the user selects a menu item.
This means that I can’t simply add similar @Override
(with different intents
) to the SettingsActivity
itself to handle my case so that the fragment does not return to the parent activity.
I’ve tried to handle this via AndroidManifest.xml
:
<activity
android:name=". SettingsActivity"
android:label="@string/title_activity_settings"
android:parentActivityName=". BlahBlahActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.appthing.BlahBlahActivity" />
</activity>
But this doesn’t seem to be doing anything at all.
What is a good (if any) good way to deal with this?
Solution
The onOptionsItemSelected method in templates created by Android Studio is fragments.
I solved this by commenting on them and writing the onOptionsItemSelected method for activities that override onBackPressed
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android. R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}