loading...

Settings - I

avinsharma profile image Avin Sharma Originally published at avinsharma.com on ・4 min read

Android Basics (8 Part Series)

1) Introduction and Setup 2) Async Task 3 ... 6 3) JSON Parsing 4) RecyclerView - I 5) RecyclerView - II, adding onClick to list items 6) Intents 7) Menu 8) 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

Add Preferences Dependency

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

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

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 might be useful if you want to find out about other preferences.

<?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 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:

    <!-- 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

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 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.

    @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:

<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

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.

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

Android Basics (8 Part Series)

1) Introduction and Setup 2) Async Task 3 ... 6 3) JSON Parsing 4) RecyclerView - I 5) RecyclerView - II, adding onClick to list items 6) Intents 7) Menu 8) Settings - I

Posted on Jun 5 by:

avinsharma profile

Avin Sharma

@avinsharma

A recent CS grad. Building an Android app. Loves ambient music and anime.

Discussion

markdown guide