PrefsFragment コピペフォーマット

![device-2016-03-05-231321.png](https://qiita-image-store.s3.amazonaws.com/0/99731/b0619c24-64ab-f4bd-ec34-a2ed755ab9dd.png)


```java:MainActivity

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.MultiSelectListPreference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.SwitchPreference;
import android.util.Log;

import java.util.Set;

public class MainActivity extends Activity {

    public static final String PREF_EDIT_KEY = "edit";
    public static final String PREF_LIST_KEY = "list";
    public static final String PREF_CHECKBOX_KEY = "checkbox";
    public static final String DEFAULT = "未設定";
    public static final String PREF_SWITCH_KEY = "switch";
    public static final String PREF_MULTI_KEY ="multi";
    public static final Boolean SWITCH_DEFAULT = true;
    public static final Boolean CHECK_BOX_DEFAULT = true;
    public static final String LIST_DEFAULT = "2";

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



        //設定画面を開く
        getFragmentManager().beginTransaction()
                        .replace(android.R.id.content, new PrefsFragment())
                        .commit();

    }
    public static class PrefsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
        CheckBoxPreference checkbox;
        SwitchPreference toggle;
        ListPreference list;
        EditTextPreference edit;
        MultiSelectListPreference multi;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);

            //今現在の設定値を取得
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());

            //チェックボックス
            checkbox = (CheckBoxPreference)getPreferenceScreen().findPreference(PREF_CHECKBOX_KEY);
            checkbox.setChecked(pref.getBoolean(PREF_CHECKBOX_KEY, CHECK_BOX_DEFAULT));
            checkbox.setSummary(checkbox.isChecked() ? "ON" : "OFF");

            //トグルスイッチ
            toggle = (SwitchPreference)getPreferenceScreen().findPreference(PREF_SWITCH_KEY);
            toggle.setChecked(pref.getBoolean(PREF_SWITCH_KEY, SWITCH_DEFAULT));
            toggle.setSummary(toggle.isChecked() ? "ON" : "OFF");

            //リスト
            list = (ListPreference)getPreferenceScreen().findPreference(PREF_LIST_KEY);
            list.setValueIndex(Integer.parseInt(pref.getString(PREF_LIST_KEY, LIST_DEFAULT)));
            int index = list.findIndexOfValue(list.getValue().toString());
            CharSequence[] entries = list.getEntries();
            list.setSummary( entries[index].toString());


            //EditText
            edit = (EditTextPreference)getPreferenceScreen().findPreference(PREF_EDIT_KEY);
            if ((edit.getText() == null) || (edit.getText().equals(""))) {
                edit.setSummary(DEFAULT);
            } else {
                edit.setSummary(edit.getText());
            }
            multi = (MultiSelectListPreference)findPreference(PREF_MULTI_KEY);
            Set values = multi.getValues();
            for (CharSequence entryValue : multi.getEntryValues()) {
                if (values.contains(entryValue)) {
                    int i = multi.findIndexOfValue(entryValue.toString());
                    if (multi.getSummary() == null) {
                        multi.setSummary(entries[i]);
                    } else {
                        multi.setSummary(multi.getSummary() + "," + entries[i]);

                    }
                }
            }
            if (multi.getSummary() == null) {
                multi.setSummary(DEFAULT);
            }

        }

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

        }
        @Override
        public void onResume() {
            super.onResume();
            getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
        }

        @Override
        public void onPause() {
            super.onPause();
            getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
        }

        //設定が変更された時に呼ばれる
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,  String key) {
            Log.d("デバッグ", "設定が変更された");
            change_pref();
        }
        private void change_pref() {

            //チェックボックス
            checkbox.setSummary(checkbox.isChecked() ? "ON" : "OFF");

            //トグルスイッチ
            toggle.setSummary(toggle.isChecked() ? "ON" : "OFF");

            //リスト
            list = (ListPreference)getPreferenceScreen().findPreference(PREF_LIST_KEY);
            int list_index = list.findIndexOfValue(list.getValue().toString());
            list.setSummary(list.getEntries()[list_index].toString());

            Log.d("デバッグ123", ":" +  edit.getText());
            //テキスト
            if ((edit.getText() == null) || (edit.getText().equals(""))) {
                edit.setSummary(DEFAULT);
            } else {
                edit.setSummary(edit.getText());
            }


            CharSequence[] entries = multi.getEntries();
            multi = (MultiSelectListPreference)findPreference(PREF_MULTI_KEY);
            multi.setSummary(null);
            Set values = multi.getValues();
            for (CharSequence entryValue : multi.getEntryValues()) {
                if (values.contains(entryValue)) {
                    int i = multi.findIndexOfValue(entryValue.toString());
                    if (multi.getSummary() == null) {
                        multi.setSummary(entries[i]);
                    } else {
                        multi.setSummary(multi.getSummary() + "," + entries[i]);
                    }
                }
            }
            if (multi.getSummary() == null) {
                multi.setSummary(DEFAULT);
            }
        }
    }



}

```

```xml:activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</LinearLayout>

```

```xml:res/xml/preferences.xml

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

    <PreferenceCategory
        android:title="設定①">

        <CheckBoxPreference
            android:key="checkbox"
            android:title="CheckBoxPreference"
            android:summary="サマリー" />

        <SwitchPreference
            android:key="switch"
            android:title="SwitchPreference"
            android:summary="サマリー" />


    </PreferenceCategory>

    <PreferenceCategory
        android:title="設定②">

        <EditTextPreference
            android:key="edit"
            android:title="EditTextPreference"
            android:dialogTitle="ダイアログのタイトル" />

        <ListPreference
            android:key="list"
            android:title="ListPreference"
            android:entries="@array/entries_list_preference"
            android:entryValues="@array/entryvalues_list_preference"
            android:dialogTitle="ダイアログのタイトル" />


        <MultiSelectListPreference
            android:key="multi"
            android:title="MultiSelectListPreference"
            android:entries="@array/entries_list_preference"
            android:entryValues="@array/entryvalues_list_preference"
            android:dialogTitle="タイトル" />

    </PreferenceCategory>

</PreferenceScreen>

```

```java:res/values/strings.xml

<resources>
    <string name="app_name">My Application</string>
    <string-array name="entries_list_preference">
        <item>犬</item>
        <item>猫</item>
        <item>鳥</item>
        <item>ゴリラ</item>
        <item>ネズミ</item>

    </string-array>
    <string-array name="entryvalues_list_preference">
        <item>0</item>
        <item>1</item>
        <item>2</item>
        <item>3</item>
        <item>4</item>

    </string-array>

</resources>

```