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
'Android' 카테고리의 다른 글
SQLite - (2) 데이터 업데이트 및 추가하기 (0) | 2018.01.06 |
---|---|
SQLite - (1) DB 생성 및 데이터 가져오기 (0) | 2018.01.06 |
Preferences - (5) List Preference (0) | 2018.01.04 |
Preferences - (4) sharedPreference 에서 값 가져오기 (0) | 2018.01.04 |
Preferences - (3) Preference Fragment 만들기 (0) | 2018.01.03 |