Preferences5.zip

Preferences_all.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
49
50
51
52
<?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...>
 
    <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 Text Size Text4"
            android:textSize="15sp"
            android:textAlignment="center"/>
        <TextView
            android:id="@+id/text4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="20dp"
            android:text="Text4"
            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 and EditTextPreference using the appropriate string resources


values/strings.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<resources>
   
    ...
 
    <!-- Label for the size preference -->
    <string name="pref_size_label">Change Text4 Size</string>
 
    <!-- Key name for storing size in SharedPreferences -->
    <string name="pref_size_key" translatable="false">size</string>
 
    <!-- Default for size preference -->
    <string name="pref_size_default" translatable="false">25</string>
</resources>
 
cs


xml/pref_settings.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <CheckBoxPreference...>
 
    <CheckBoxPreference...>
 
    <ListPreference...>
 
    <EditTextPreference
        android:defaultValue="@string/pref_size_default"
        android:key="@string/pref_size_key"
        android:title="@string/pref_size_label" />
    
</PreferenceScreen>
cs




3. Modify the setupSharedPreferences method to use the new preference value

   Modify onSharedPreferencesChanged to parse the preference value

   Modify setPreferenceSummary for an EditTextPreference


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
100
101
102
103
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, textView4;
 
    @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);
        textView4 = findViewById(R.id.text4);
 
        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){...}
 
    // text4 세팅 (Size)
    private void setTextSize(float newSize){
        textView4.setTextSize(newSize);
    }
 
    // 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)));
 
        // text4 세팅 (Size)
        setTextSize(Float.parseFloat(sharedPreferences.getString(getString(R.string.pref_size_key),
                getString(R.string.pref_size_default))));
 
        /*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)));
        }
        else if(key.equals(getString(R.string.pref_size_key))) {
            setTextSize(Float.parseFloat(sharedPreferences.getString(getString(R.string.pref_size_key),
                    getString(R.string.pref_size_default))));
        }
    }
 
    @Override
    protected void onDestroy() {...}
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {...}
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {...}
}
 
cs



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
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) {...}
 
    /**
     * 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]);
            }
        }
        else if (preference instanceof EditTextPreference) {
            // EditTextPreferences 에서 value 를 summary 에 세팅
            preference.setSummary(value);
        }
    }
 
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {...}
 
    @Override
    public void onCreate(Bundle savedInstanceState) {...}
 
    @Override
    public void onDestroy() {...}
}
 
cs





예외처리

4. Update SettingsFragment to implement onPreferenceChangeListener

   Override onPreferenceChange to convert the Preference value to float and 

    show an error message if it failed to do so

   Add the onPreferenceChangeListener specifically to the EditTextPreference


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
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;
import android.widget.Toast;
 
/*
 * SharedPreferencesChangeListener: 모든 값이 SharedPreferences 파일에 저장되면 트리거된다.
 * PreferenceChangeListener: 값이 SharedPreferences 파일에 저장되기 전에 트리거된다.
 *                           이로 인해 유효하지 않은 업데이트를 방지할 수 있다.
 * */
public class SettingsFragment extends PreferenceFragmentCompat
        implements SharedPreferences.OnSharedPreferenceChangeListener, Preference.OnPreferenceChangeListener {
 
    @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 listener 추가
        Preference preference = findPreference(getString(R.string.pref_size_key));
        preference.setOnPreferenceChangeListener(this);
    }
 
    private void setPreferenceSummary(Preference preference, String value) {...}
 
    
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {...}
 
    // 바뀐 preference 의 크기가 올바른지 확인
    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
 
        String sizeKey = getString(R.string.pref_size_key);
 
        if (preference.getKey().equals(sizeKey)) {
            String stringSize = (String) newValue;
            try {
                float size = Float.parseFloat(stringSize);
                // 숫자가 허용 범위를 벗어나면 토스트 표시
                if (size > 50 || size <= 0) {
                    Toast.makeText(getContext(), "0과 50 사이에 숫자를 입력해주세요.", Toast.LENGTH_SHORT).show();
                    return false;
                }
            } catch (NumberFormatException nfe) {
                // 사용자가 입력한 내용을 숫자로 파싱 할 수 없는 경우 토스트 표시
                Toast.makeText(getContext(), "0과 50 사이에 숫자를 입력해주세요.", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }
 
    @Override
    public void onCreate(Bundle savedInstanceState) {...}
 
    @Override
    public void onDestroy() {...}
}
 
cs




Android Course of Udacity - Lesson 6

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

Preferences3.zip


0. Result


   





1. Using PreferenceManager, get the default SharedPreference

   Set setTextView() based on the value from the SharedPreference


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
package com.tistory.qlyh8.preferences;
 
import android.content.Intent;
import android.content.SharedPreferences;
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 {
 
    TextView textView1, textView2;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView1 = findViewById(R.id.text1);
        textView2 = findViewById(R.id.text2);
 
        setupSharedPreferences();
    }
 
    // text1 세팅 (Shown / Hidden)
    private void setTextView1(boolean isTrue){
        if(isTrue)
            textView1.setText("Text1");
        else
            textView1.setText("");
    }
 
    // text2 세팅 (Shown / Hidden)
    private void setTextView2(boolean isTrue){
        if(isTrue)
            textView2.setText("Text2");
        else
            textView2.setText("");
    }
 
    // 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)));
 
        /*SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(getString(R.string.pref_show_text1_key), getResources().getBoolean(R.bool.pref_show_text1_default));
        editor.apply();*/
    }
...
}
 
cs





2. Implement OnShardPreferenceChangeListener

   Override the onSharedPreferenceChanged method and update the show textView preference

   Register the listener

   Override onDestory and unregister the listener


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
package com.tistory.qlyh8.preferences;
 
import android.content.Intent;
import android.content.SharedPreferences;
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;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView1 = findViewById(R.id.text1);
        textView2 = findViewById(R.id.text2);
 
        setupSharedPreferences();
    }
 
    // text1 세팅 (Shown / Hidden)
    private void setTextView1(boolean isTrue){...}
 
    // text2 세팅 (Shown / Hidden)
    private void setTextView2(boolean isTrue){...}
 
    // 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)));
 
        /*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)));
        }
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //리스너 해지
        PreferenceManager.getDefaultSharedPreferences(this)
                .unregisterOnSharedPreferenceChangeListener(this);
    }
 
    //메뉴 생성
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {...}
 
    //메뉴의 항목이 선택되었을 때 호출
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {...}
}
 
cs




Android Course of Udacity - Lesson 6

+ Recent posts