Setting Preference Activity In Android Q.

In this article, we are going to learn how we can use setting preference activity in Android. When we need certain settings in our app.

What is Setting Preference Activity?

Setting Activity is an activity in the android studio which makes it easy to integrate the functionality and user interface in the application.

Use of Setting Preference Activity in Android.

Many times we need certain settings in our app, like setting default language, theme(light or dark), customizing notifications, etc.

In this tutorial, we will be creating a simple app with settings to change Image visibility.

But, For this, we will be using Shared Preferences.

In this article, we will be creating the first setting that is making the image visible or invisible by CheckBoxPreference.

Example For Setting Preference Activity in Android.

1:- Create a new android project.

File –> New –> Activity –> EmptyActivity –> name the project(SettingPrefrence) –>finish.

2:- In res/menu create a .xml file.

Right-click on the menu –> New –> menu resource file –> name the file(menu_item.xml) –>ok.

3:- In menu_item.xml copy the below code.

//menu_item.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="setting"
        app:showAsAction="never" />
</menu>

4:- In MainActivity.java write the below code for creating and selection of menu items.

when we click on settings then the following methods will be called.

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_item, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            // launch settings activity
            startActivity(new Intent(MainActivity.this, SettingsActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

5:-  Now in activity_main.xml write below code for text view and image view.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="10dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Setting Prefrence"
        android:textColor="#000000"
        android:textSize="25dp"
        android:gravity="center_horizontal"/>

    <ImageView
        android:id="@+id/image"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:src="@drawable/image"
        android:layout_centerInParent="true"/>



</RelativeLayout>

6:- Now for Setting activity.

Right-click on the app –> new –> activity –> setting activity –>finish.

public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settings, new SettingsFragment())
                .commit();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);
        }
    }
}

And, you will get the above code in setting activity by default.

7:- Now, In rex/xml/root_preferences.xml copy the below code in your file for SwitchPreferenceCompat.

<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">

    <SwitchPreferenceCompat
        app:key="display_image"
        app:defaultValue="true"
        app:summary="Visible/Invisible Image"
        app:title="Display Image" />

</PreferenceScreen>

Attributes define:-

key = used for the id of the view.

defaultValue = true/false for making switch initially on/off. By default it is true.

summary = to provide a short description of the switch button.

title = to provide title/name of the switch button.

8:- In MainActivity file.

Now, implements your MainActivity file with SharedPreferences.OnSharedPreferenceChangeListener and copy the below code in your file.

public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    ImageView image;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = findViewById(R.id.image);
        ActionBar actionBar = this.getSupportActionBar();

        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        setupSharedPreferences();
    }

    private void setImageVisible(boolean display_image) {
        if (display_image == true) {
            image.setVisibility(View.VISIBLE);
        } else {
            image.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_item, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            // launch settings activity
            startActivity(new Intent(MainActivity.this, SettingsActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {


        if (key.equals("display_image")) {
            setImageVisible(sharedPreferences.getBoolean("display_image",true));
        }

    }
    private void setupSharedPreferences() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);
    }

Here, the description of the above methods uses in the MainActivity file.

private void setupSharedPreferences() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);
    }

Here, the Above method is used to set the switch button preference. It set true when on and false when off.

@Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {


        if (key.equals("display_image")) {
            setTextVisible(sharedPreferences.getBoolean("display_image",true));
        }

    }

Now, The above method is used to getting the preference data on switch button status changed.
It gets true when on and false when off.

and now,

private void setImageVisible(boolean display_image) {
        if (display_image) {
            image.setVisibility(View.VISIBLE);
        } else {
            image.setVisibility(View.INVISIBLE);
        }
    }

This method is used to set the visibility of the image. The image will visible when the switch button in on.

But,

The image will invisible when the switch button is off.

Now, you can run your project and you will get the following output.

Output:-

Now, when you turn on the switch button image will be visible.

And, I hope this article will helpful for you.

Thank you.

2 thoughts on “Setting Preference Activity In Android Q.

Leave a Reply

Your email address will not be published. Required fields are marked *