Roman
Roman

Reputation: 3149

Android Studio - Settings Activity with just one fragment/no Headers

I am new to android development and am facing a problem: I have a normal tabbed MainActivity and created a SettingsActivity from the settings activity Template of Android Studio. The MainActivity is the hierarchical parent of SettingsActivity.

Code to start the SettingsActivity in MainActivity.java:

 Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);

I only want to have ONE settings page. As of Android Guidelines "addPreferencesFromResource();" is deprecated and got replaced by Preference headers. But with these preference headers i get one more page between my MainActivity and my actuall settings page (defined in pref_settings.xml) After googling around how to get rid of this extra page, I came up with this statement in the SettingsActivity.java in the onCreate Method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setupActionBar();

    getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new PillPreferenceFragment())
            .commit();
}

Well, it does solve my problem. The pref_settings.xml is displayed when starting the SettingsActivity. But the back button doesn't work anymore. It always goes "back" to the SettingsActivity and not to the MainActivity. So this is an endless loop. Does anyone know what is the problem and how to solve it?

I hope, my description is understandable. If you need any further information, please tell me.

Thanks a lot in advance! :)

Upvotes: 2

Views: 1235

Answers (2)

Roman
Roman

Reputation: 3149

I found a solution by myself.

I had to add this code in SettingsActivity.java:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        this.finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Upvotes: 2

rodoboss
rodoboss

Reputation: 17

Try this code below:

Intent i = new Intent(getApplicationContext(), SettingsActivity.class);
            startActivity(i);
            finish();

add this line in android manifest in application tag:

 android:launchMode="singleTask"

and don't forget to override the back press button:

@Override
    public void onBackPressed() {
    super.onBackPressed();
    }

Upvotes: 0

Related Questions