Preferences4.zip


0. Result


   





1. Add TextView to activity_main.xml


layout/activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?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"
    tools:context="com.tistory.qlyh8.preferences.MainActivity">
 
    <LinearLayout...>
 
    <View...>
 
    <LinearLayout...>
 
    <View...>
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical"
        android:padding="10dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Change Color(Red/Blue/Green) Text3"
            android:textSize="15sp"
            android:textAlignment="center"/>
        <TextView
            android:id="@+id/text3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="20dp"
            android:text="Text3"
            android:textSize="25sp"
            android:textStyle="bold"
            android:textAlignment="center"/>
    </LinearLayout>
 
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#000" />
 
</LinearLayout>
 
cs





2. Add string resources for the list preference


values/strings.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<resources>
    
    ...
 
    <!-- Label for the color preference -->
    <string name="pref_color_label">Change Text3 Color</string>
 
    <!-- Label for red color preference -->
    <string name="pref_color_label_red">Red</string>
    <!-- Label for blue color preference -->
    <string name="pref_color_label_blue">Blue</string>
    <!-- Label for green color preference -->
    <string name="pref_color_label_green">Green</string>
 
    <!-- Key name for color preference in SharedPreferences -->
    <string name="pref_color_key" translatable="false">color</string>
 
    <!-- Value in SharedPreferences for red color option -->
    <string name="pref_color_red_value" translatable="false">red</string>
    <!-- Value in SharedPreferences for blue color option -->
    <string name="pref_color_blue_value" translatable="false">blue</string>
    <!-- Value in SharedPreferences for green color option -->
    <string name="pref_color_green_value" translatable="false">green</string>
</resources>
 
cs





3. Create the arrays.xml resource file to contain arrays for lables and values


values/arrays.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="pref_color_option_labels">
        <item>@string/pref_color_label_red</item>
        <item>@string/pref_color_label_blue</item>
        <item>@string/pref_color_label_green</item>
    </array>
 
    <array name="pref_color_option_values">
        <item>@string/pref_color_red_value</item>
        <item>@string/pref_color_blue_value</item>
        <item>@string/pref_color_green_value</item>
    </array>
</resources>
cs





4. Add a list preference to pref_settings.xml


pref_settings.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    
    <CheckBoxPreference...>
 
    <CheckBoxPreference...>
 
    <!-- entries:Array with all the option labels
         entryValues: Array with all the values -->
    <ListPreference
        android:defaultValue="@string/pref_color_red_value"
        android:key="@string/pref_color_key"
        android:entries="@array/pref_color_option_labels"
        android:entryValues="@array/pref_color_option_values"
        android:title="@string/pref_color_label" />
 
</PreferenceScreen>
cs





5. Update onSharedPreferenceChanged to load the color


values/colors.xml

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="utf-8"?>
<resources>
    
    ...
 
    <color name="colorRed">#FF0000</color>
    <color name="colorBlue">#0000FF</color>
    <color name="colorGreen">#00FF00</color>
</resources>
 
cs



MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.tistory.qlyh8.preferences;
 
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
 
public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
 
    TextView textView1, textView2, textView3;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView1 = findViewById(R.id.text1);
        textView2 = findViewById(R.id.text2);
        textView3 = findViewById(R.id.text3);
 
        setupSharedPreferences();
    }
 
    // text1 세팅 (Shown / Hidden)
    private void setTextView1(boolean isTrue){...}
 
    // text2 세팅 (Shown / Hidden)
    private void setTextView2(boolean isTrue){...}
 
    // text3 세팅 (Red / Blue / Green)
    private void setTextColor(String newTextColor){
        if (newTextColor.equals(getString(R.string.pref_color_blue_value))) {
            textView3.setTextColor(ContextCompat.getColor(getBaseContext(), R.color.colorBlue));
        } else if (newTextColor.equals(getString(R.string.pref_color_green_value))) {
            textView3.setTextColor(ContextCompat.getColor(getBaseContext(), R.color.colorGreen));
        } else {
            textView3.setTextColor(ContextCompat.getColor(getBaseContext(), R.color.colorRed));
        }
    }
 
    // SharedPreferences 에서 모든 값을 가져 와서 설정
    private void setupSharedPreferences() {
        SharedPreferences sharedPreferences
                = PreferenceManager.getDefaultSharedPreferences(this);
 
        // text1 세팅 (Shown / Hidden)
        setTextView1(sharedPreferences.getBoolean(getString(R.string.pref_show_text1_key),
                getResources().getBoolean(R.bool.pref_show_text1_default)));
 
        // text2 세팅 (Shown / Hidden)
        setTextView2(sharedPreferences.getBoolean(getString(R.string.pref_show_text2_key),
                getResources().getBoolean(R.bool.pref_show_text2_default)));
 
        // text3 세팅 (Red / Blue / Green)
        setTextColor(sharedPreferences.getString(getString(R.string.pref_color_key),
                getString(R.string.pref_color_red_value)));
 
        /*SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(getString(R.string.pref_show_text1_key), getResources().getBoolean(R.bool.pref_show_text1_default));
        editor.apply();*/
 
        // 리스너 등록
        // 리스너를 implement 해주었기 때문에 this
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);
    }
 
    // shared preferences 이 변경되면 화면을 업데이트
    // OnSharedPreferenceChangedListener 를 구현하는 클래스를 만들 때 이 메서드가 필요
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if(key.equals(getString(R.string.pref_show_text1_key))) {
            setTextView1(sharedPreferences.getBoolean(key, getResources().getBoolean(R.bool.pref_show_text1_default)));
        }
        else if(key.equals(getString(R.string.pref_show_text2_key))) {
            setTextView2(sharedPreferences.getBoolean(key, getResources().getBoolean(R.bool.pref_show_text2_default)));
        }
        else if(key.equals(getString(R.string.pref_color_key))) {
            setTextColor(sharedPreferences.getString(getString(R.string.pref_color_key),
                    getString(R.string.pref_color_red_value)));
        }
    }
 
    @Override
    protected void onDestroy() {...}
 
    //메뉴 생성
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {...}
 
    //메뉴의 항목이 선택되었을 때 호출
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {...}
}
 
cs




List Preference 의 Summary 설정

6. Implement OnSharedPreferenceChangeListener

   In onCreatePreferences, iterate over the preferences and 

   call setPreferenceSummary for anything not checkbox

   Override onSharedPreferenceChanged and handle preferences that are not of type checkbox

   Register and unRegister the OnSharedPreferenceChange listener


SettingsFragment.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.tistory.qlyh8.preferences;
 
/*
 * Created by YUNHEE on 2018-01-03.
 */
 
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.preference.CheckBoxPreference;
import android.support.v7.preference.EditTextPreference;
import android.support.v7.preference.ListPreference;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.support.v7.preference.PreferenceScreen;
 
public class SettingsFragment extends PreferenceFragmentCompat
        implements SharedPreferences.OnSharedPreferenceChangeListener {
 
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.pref_settings);
 
        SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences();
 
        // PreferenceScreen 을 이용해 총 Preference 개수를 알 수 있다.
        PreferenceScreen prefScreen = getPreferenceScreen();
        int count = prefScreen.getPreferenceCount();
 
        // 모든 preferences 가 checkbox preference 이 아니면 setSummary 메소드를 호출하여
        // preference 및 preference 값 전달
        for (int i = 0; i < count; i++) {
            Preference p = prefScreen.getPreference(i);
            // checkbox preferences 는 이미 summaryOff 와 summary On 를 가지고 있기 때문에 제외
            if (!(p instanceof CheckBoxPreference)) {
                String value = sharedPreferences.getString(p.getKey(), "");
                setPreferenceSummary(p, value);
            }
        }
    }
 
    /**
     * preference 의 summary 를 갱신한다.
     * preference 가 ListPreference 인지 체크하고
     * ListPreference 일 경우에 그 값과 관련된 label 을 찾는다.
     * @param preference: 갱신할 preference
     * @param value:      갱신될 preference 의 값
     */
    private void setPreferenceSummary(Preference preference, String value) {
        // ListPreference 인지,  EditTextPreferences 인지 검사
        if (preference instanceof ListPreference) {
            // ListPreference 에서 선택된 값의 label 을 검색
            ListPreference listPreference = (ListPreference) preference;
 
            int prefIndex = listPreference.findIndexOfValue(value);
            //prefIndex 값의 유효 체크
            if (prefIndex >= 0) {
                // summary 에 해당 label 을 세팅
                listPreference.setSummary(listPreference.getEntries()[prefIndex]);
            }
        }
    }
 
    // 바뀐 preference 의 summary 갱신
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        // 바뀐 preference 검색
        Preference preference = findPreference(key);
 
        if (preference != null) {
            if (!(preference instanceof CheckBoxPreference)) {
                // preference 의 summary 갱신
                String value = sharedPreferences.getString(preference.getKey(), "");
                setPreferenceSummary(preference, value);
            }
        }
    }
 
    // PreferenceScreen 을 불러와서 onSharedPreferenceChanged 리스너 등록
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getPreferenceScreen().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
    }
 
    // PreferenceScreen 을 불러와서 onSharedPreferenceChanged 리스너 해지
    @Override
    public void onDestroy() {
        super.onDestroy();
        getPreferenceScreen().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }
}
 
cs




Android Course of Udacity - Lesson 6

+ Recent posts