Thursday, November 23, 2017

android - SwitchPreference OnPreferenceChange listener example

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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:orientation="vertical"
    >
    <Button
        android:id="@+id/button_do_task"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Settings"
        />
</LinearLayout>
MainActivity.java

package com.cfsuman.androidcode;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private Button mButton;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widgets reference from xml layout
        mButton = findViewById(R.id.button_do_task);


        // Set a click listener for button widget
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Initialize an intent
                Intent settingsIntent = new Intent(mContext,ActivitySettings.class);

                // Start the activity
                startActivity(settingsIntent);
            }
        });
    }
}

SettingsFragment.java

package com.cfsuman.androidcode;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.SwitchPreference;
import android.widget.Toast;



public class SettingsFragment extends PreferenceFragment {
    private Context mContext;
    private Activity mActivity;


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

        addPreferencesFromResource(R.xml.preferences);


        // Get the application context
        mContext = this.getActivity();
        mActivity = this.getActivity();

        /*
            SwitchPreference
                This preference will store a boolean into the SharedPreferences.
        */

        // Get the preference widgets reference
        final SwitchPreference onOffRandomColor = (SwitchPreference) findPreference(this.getResources()
                                                    .getString(R.string.sp_key_on_off_random_color));

        /*
            void setOnPreferenceChangeListener (Preference.OnPreferenceChangeListener onPreferenceChangeListener)
                Sets the callback to be invoked when this Preference is changed by the user
                (but before the internal state has been updated).

            Parameters
                onPreferenceChangeListener Preference.OnPreferenceChangeListener: The callback to be invoked.
        */

        // SwitchPreference preference change listener
        onOffRandomColor.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object o) {
                if(onOffRandomColor.isChecked()){
                    Toast.makeText(mActivity,"Unchecked",Toast.LENGTH_SHORT).show();

                    // Checked the switch programmatically
                    onOffRandomColor.setChecked(false);
                }else {
                    Toast.makeText(mActivity,"Checked",Toast.LENGTH_SHORT).show();

                    // Unchecked the switch programmatically
                    onOffRandomColor.setChecked(true);
                }
                return false;
            }
        });
    }
}
res/xml/preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <SwitchPreference
        android:key="@string/sp_key_on_off_random_color"
        android:title="@string/sp_title_on_off_random_color"
        android:defaultValue="true"
        android:icon="@drawable/ic_color_lens_black_24dp"
        />
</PreferenceScreen>
res/values/strings.xml

<resources>
    <string name="app_name">Android Code</string>
    <string name="title_activity_setting">Settings</string>

    <!-- preference -->
    <string name="sp_key_on_off_random_color">key_on_off_random_color</string>
    <string name="sp_title_on_off_random_color">Enable/Disable Random Color</string>

</resources>