Question

I'm setting up some basic settings for my android application, and I'm having some problems. First of all, I couldn't figure out how to use the triple-dot menu in the top right of the action bar to open Settings. So I temporarily created a button that calls chooseSettings:

a button

    public void chooseSettings(View view) {
    getFragmentManager().beginTransaction().replace(android.R.id.content, new PreferenceActivity()).commit();
}

This is the code for my PreferenceActivity class:

public class PreferenceActivity extends PreferenceFragment {
@Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preferences);
 }
}

Which kind of works. That results in my screen looking like this:.

this

Was it helpful?

Solution

Settings in Overflow Menu

In order to use the Settings in the overflow menu, you need to override the onOptionsItemSelected method, if not already and handle the correct id.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        // Code to show settings.
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Replace R.id.action_settings with the id of your menu item.

Displaying the PreferenceFragment

As you have shown in your image, your preferences screen is overlapping the existing layout.

Note that you can only replace a fragment you added dynamically.

I'm guessing the xml for your screen that has the buttons Guess Country and Guess Flags was inflated and was not dynamically added as a fragment so by adding the preference fragment it would simply be displayed overlapping.

Solution

One way you can go about this is by creating and starting a new activity which will load your preferences fragment.

For example, if you create class called SettingsActivity which will load the preferences (Don't forget to add to AndroidManifest):

public class SettingsActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new PreferenceActivity()).commit();
    }
}

Then in your onOptionsItemSelected, you can start the settings activity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Otherwise, you would need to change your main layout to use something like a frame layout so that you can add/remove/replace fragments properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top