Settings - I
Tags: android, androiddevelopment, beginners, androiddev
Published: 2020-06-05 21:58:42

---
title: Settings - I
published: true
date: 2020-06-05 00:00:00 UTC
tags: android, androiddevelopment, beginners, androiddev
series: Android Basics
canonical_url: https://avinsharma.com/android-basics-settings-I/
---

In the previous post we created a menu with a single element with the title “Settings”. In this post we are going to create a settings screen and connect it to the settings option in the menu. You can get the code for everything we have done till now [here](https://github.com/avin-sharma/Github-Repository-Search/tree/menu)

## Add Preferences Dependency

Add the following to the app level build.gradle and then sync it.

```java
implementation 'androidx.preference:preference:1.1.1'
```

## Create a Settings Activity

We want to create an Activity that launches when the settings option is clicked. The settings activity will be the child of MainActivity, we do this so that when we press back from the settings activity we go back to the MainActivity.

Let’s create an Empty Activity and name it `SettingsActivity`, change from EmptyActivity to SettingsActivity.

[![settings-activity](https://avinsharma.com/static/fb6b15fbf506dad02b5f46959a63388a/799d3/settings-activity.png "settings-activity")](/static/fb6b15fbf506dad02b5f46959a63388a/2bfc9/settings-activity.png)

We will add a fragment to the xml of this activity later when we have our fragment ready.

## Create Settings Preferences XML

The XML we are going to create now controls how our settings looks and all the values in it. This xml file has to be in a resource directory called xml `(res/xml/settings_pref.xml)`. So let’s create a resource directory called xml and add an xml file called `settings_pref.xml`.

Here we are creating a ListPreference because we want to select a single option out of many there are other preferences like SwitchPreference, MultiSelectListPreference, etc. This [link](https://developer.android.com/guide/topics/ui/settings/components-and-attributes#individual_preferences) might be useful if you want to find out about other preferences.

```xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android">

    <ListPreference
        android:title="Sort By"
        android:key="sort-by"
        android:defaultValue="@string/pref_sort_by_key_default"
        android:entries="@array/pref_repo_sort_by_option_labels"
        android:entryValues="@array/pref_repo_sort_by_option_values"
        android:summary="@string/pref_sort_by_summary"/>
    
</PreferenceScreen>
```

I have created all the strings in `res/values/strings.xml` and created another file `res/values/arrays.xml` where I created the two arrays I am using for entries and entryValues. This is what my arrays look like:

```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="pref_repo_sort_by_option_labels">
        <item>@string/pref_sort_by_label_default</item>
        <item>@string/pref_sort_by_label_stars</item>
        <item>@string/pref_sort_by_label_forks</item>
        <item>@string/pref_sort_by_label_updated</item>
        <item>@string/pref_sort_by_label_help_wanted_issues</item>
    </array>

    <array name="pref_repo_sort_by_option_values">
        <item>@string/pref_sort_by_key_default</item>
        <item>@string/pref_sort_by_key_stars</item>
        <item>@string/pref_sort_by_key_forks</item>
        <item>@string/pref_sort_by_key_updated</item>
        <item>@string/pref_sort_by_key_help_wanted_issues</item>
    </array>
</resources>
```

and the strings like so:

```xml
    <!-- Sort By List Preference Strings -->
    <string name="pref_sort_by_summary">Select which parameter to sort the results of the query by</string>
    <string name="pref_sort_by_key" translatable="false">sort-by</string>
    <string name="pref_sort_by_label">Sort By</string>
    
    <string name="pref_sort_by_label_default">Default</string>
    <string name="pref_sort_by_label_stars">Stars</string>
    <string name="pref_sort_by_label_forks">Forks</string>
    <string name="pref_sort_by_label_updated">Recently Updated</string>
    <string name="pref_sort_by_label_help_wanted_issues">Help Wanted Issues</string>

    <string name="pref_sort_by_key_default">default</string>
    <string name="pref_sort_by_key_stars">stars</string>
    <string name="pref_sort_by_key_forks">forks</string>
    <string name="pref_sort_by_key_updated">updated</string>
    <string name="pref_sort_by_key_help_wanted_issues">help-wanted-issues</string>
```

Entries is what will be shown in the settings and entryValues is their corresponding keys that we will use in the code later. One important thing to note here is that the order of the items in both the arrays should be the same.

## Create SettingsFragment

Create a new class in the same directory as the MainActivity called SettingsFragment which extends `PreferenceFragmentCompat`

```java
package com.avinsharma.githubrepositorysearch;

import android.os.Bundle;

import androidx.preference.PreferenceFragmentCompat;

public class SettingsFragment extends PreferenceFragmentCompat {
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.settings_pref);
    }
}
```

## Add the newly created Fragment to SettingsActivity XML

In the `activity_settings.xml`

```xml
<?xml version="1.0" encoding="utf-8"?>
<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="com.avinsharma.githubrepositorysearch.SettingsFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
```

## Launch SettingsActivity on settings menu option click

Now instead of a Toast we want to launch the SettingsActivity from the MainActivity when settings menu option is clicked.

```java
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.settings_menu_option:
                Intent intent = new Intent(this, SettingsActivity.class);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
```

## Finally make MainActivity the parent of SettingsActivity in the Manifest

We want SettingsActivity to be the child Activity of MainActivity so that android gives us a back button on the UI and also know where to go back to.

In the manifest we add `parentActivityName` to the SettingsActivity:

```java
<activity android:name=".SettingsActivity"
            android:parentActivityName=".MainActivity"></activity>
```

## Conclusion

To summarize do the following steps to create simple settings

1. Add Dependency
2. Create a Settings Activity
3. Create Settings Preferences XML
4. Create SettingsFragment
5. Add the newly created Fragment to SettingsActivity XML
6. Launch SettingsActivity on settings menu option click
7. Finally make MainActivity the parent of SettingsActivity in the Manifest

This is what our settings looks like right now:

[![app](https://avinsharma.com/static/ca02d2c01b83c4211301c39c6d26223f/799d3/app.png "app")](/static/ca02d2c01b83c4211301c39c6d26223f/9d22c/app.png)

We have created settings for our app where we offer different ways to sort the github queries but nothing happens when we choose a different option. In the next post we will explore how to detect changes in settings and how to get the current selected settings using SharedPreferences.

You can find the code for everything done up till now [here](https://github.com/avin-sharma/Github-Repository-Search/tree/settings-I).

As always if you find any errors, have feedback or just want to say hi please don’t hesitate to leave a comment below.