Java – rise from preferencearag and preferencefragments using optionsitemselected

I'm having trouble using optionsitemselected when using Android studio's default set activity (extended appcompatpreferenceactivity) Important parts of the activity are:

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 useful for clips – onoptionsitemselected @ overrides works well and returns to settingsactivity, but when using the up button, I want settingsactivity to return control to its parent activity

I've read the document and I understand

This means that I can't simply add a similar @ override (using a different intent) to the settingsactivity itself to handle the situation I want, so as not to return the fragment to the parent activity

I tried Android manifest XML handles this:

<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 it doesn't seem to do anything at all

If so, what is a good way to deal with this problem?

Solution

It belongs to a fragment in the template created by the Android studio optionsitemselected method

I solved this by commenting on them and writing the onoptionsitemselected method for the activity that overrides 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);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>