We can add SwitchPreference to PreferenceScreen in xml like below in android
R.xml.switch_preference.xml
We have to use PreferenceFragment to access this xml like below. SwitchPreference.java
Detailed video tutorial
I hope this post is useful to you. kindly share your feedback as comment here.
Thank You
R.xml.switch_preference.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<SwitchPreference
android:key="switch"
android:summaryOff="Switch off"
android:summaryOn="Switch on"
android:title="Switch Preference" />
</PreferenceScreen>
We have to use PreferenceFragment to access this xml like below. SwitchPreference.java
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.widget.Toast;
/**
* Created by Guna on 05-10-2017.
*/
public class SwitchPreference extends PreferenceFragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.switch_preference);
}
@Override
public void onResume() {
super.onResume();
//You can change preference summary programmatically like following.
android.preference.SwitchPreference preference = (android.preference.SwitchPreference) findPreference("switch");
preference.setSummaryOff("Switch off state updated from code");
preference.setSummaryOn("Switch on state updated from code");
//You can read preference value anywhere in the app like following.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
boolean isChecked = sharedPreferences.getBoolean("switch", false);
Toast.makeText(getActivity(), "isChecked : " + isChecked, Toast.LENGTH_LONG).show();
}
}
Detailed video tutorial
I hope this post is useful to you. kindly share your feedback as comment here.
Thank You
Can you provide the source code for above video example
ReplyDelete