Preferences2.zip


0. Result




1. Add the gradle dependency for the support preference fragment


app/build.gradle

1
2
3
dependencies {
    compile 'com.android.support:preference-v7:26.1.0'
}
cs





2. Create the pref_settings in res/xml and

   Add a CheckBoxPreference to the preference


values/strings.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<resources>
   
    <!-- Label for the show text1 checkbox preference -->
    <string name="pref_show_text1_label">Show Text1</string>
    <!-- Key name for storing text1 in SharedPreferences -->
    <string name="pref_show_text1_key" translatable="false">show_text1</string>
    <!-- Label for the show text2 checkbox preference -->
    <string name="pref_show_text2_label">Show Text2</string>
    <!-- Key name for storing text2 in SharedPreferences -->
    <string name="pref_show_text2_key" translatable="false">show_text2</string>
 
    <!-- Summary for Checkboxes -->
    <string name="pref_show_true">Shown</string>
    <string name="pref_show_false">Hidden</string>
</resources>
 
cs



values/bools.xml

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="pref_show_text1_default">true</bool>
    <bool name="pref_show_text2_default">false</bool>
</resources>
cs



xml/pref_settings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="utf-8"?>
<!-- 계층적인 구조를 만들고 싶을 경우, preferenceScreen 태그 안에
     preferenceScreen 태그를 중복해서 사용하면 된다.-->
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- defaultValue: 기본적으로 설정할 값
         summary: 체크박스가 어떤 역할을 하는지 유저에게 설명한다.
         여기선 summaryOn 일때 보이게, summaryOff 일때 안보이게 설정 -->
    <CheckBoxPreference
        android:defaultValue="@bool/pref_show_text1_default"
        android:key="@string/pref_show_text1_key"
        android:summaryOff="@string/pref_show_false"
        android:summaryOn="@string/pref_show_true"
        android:title="@string/pref_show_text1_label" />
 
    <CheckBoxPreference
        android:defaultValue="@bool/pref_show_text2_default"
        android:key="@string/pref_show_text2_key"
        android:summaryOff="@string/pref_show_false"
        android:summaryOn="@string/pref_show_true"
        android:title="@string/pref_show_text2_label" />
 
</PreferenceScreen>
cs





3. Create the SettingsFragment class that extends PreferencesFragmentCompat and

    Call add PreferencesFromResource method to add the preference file


SettingsFragment.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.tistory.qlyh8.preferences;
 
/*
 * Created by YUNHEE on 2018-01-03.
 */
 
import android.os.Bundle;
import android.support.v7.preference.PreferenceFragmentCompat;
 
public class SettingsFragment extends PreferenceFragmentCompat {
 
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.pref_settings);
    }
}
 
cs





4.  Set the root layout of activity_settings to the newly created SettingsFragment


layout/activity_settings.xml

1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_settings"
    android:name="com.tistory.qlyh8.preferences.SettingsFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
cs





5. Add a preference theme to styles.xml


values/styles.xml

1
2
<!-- PreferenceFragmentCompat 라이브러리를 사용하기 때문에 추가 -->
<item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
cs




Android Course of Udacity - Lesson 6

Preferences1.zip


0. Result


 




1. Add TextView in 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?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
        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="Shown / Hidden Text1 (Default: Shown)"
            android:textSize="15sp"
            android:textAlignment="center"/>
        <TextView
            android:id="@+id/text1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="20dp"
            android:text="Text1"
            android:textSize="25sp"
            android:textStyle="bold"
            android:textAlignment="center"
            android:gravity="center" />
    </LinearLayout>
 
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#000" />
 
    <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="Shown / Hidden Text2 (Default: Hidden)"
            android:textSize="15sp"
            android:textAlignment="center"/>
        <TextView
            android:id="@+id/text2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="20dp"
            android:text="Text2"
            android:textSize="25sp"
            android:textStyle="bold"
            android:textAlignment="center"
            android:gravity="center"/>
    </LinearLayout>
 
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#000" />
 
</LinearLayout>
 
cs





2. Create a new layout called activity_settings and

   Create a new Activity called SettingsActivity


layout/activity_settings.xml

1
2
3
4
5
6
7
<?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>
 
cs



SettingsActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.tistory.qlyh8.preferences;
 
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
 
/*
 * Created by YUNHEE on 2018-01-03.
 */
 
public class SettingsActivity extends AppCompatActivity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
    }
}
 
cs





3. Create a new resource folder called menu and

   Create settings_menu.xml in menu and add a menu item in it


Resource type: menu


values/strings.xml

1
<string name="action_settings">Settings</string>
cs



menu/settings_menu.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
 
    <!--우선도를 100으로 정하고, 액션바에서는 보이지 않게 함 -->
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
 
</menu>
cs





4. Add the menu to the menu bar and

   Handle "Settings" menu item click to open SettingsActivity


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
package com.tistory.qlyh8.preferences;
 
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    //메뉴 생성
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.settings_menu, menu);
        return true;
    }
 
    //메뉴의 항목이 선택되었을 때 호출
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        //"settings" 메뉴
        if(id == R.id.action_settings){
            startActivity(new Intent(this, SettingsActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
 
cs



manifests/AndroidManifest.xml


mainActivity의 launchMode 를 singleTop으로 설정하고

SettingsActivity의 부모 액티비티를 MainActivity 로 설정한다.

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
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tistory.qlyh8.preferences">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!-- singleTop: SettingActivity 에서 돌아왔을 때 MainActivity 를 다시 생성하지 않게 함 -->
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 
        <activity
            android:name=".SettingsActivity"
            android:label="@string/action_settings"
            android:parentActivityName=".MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
    </application>
 
</manifest>
cs



SettingsActivity.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
package com.tistory.qlyh8.preferences;
 
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
 
/*
 * Created by YUNHEE on 2018-01-03.
 */
 
public class SettingsActivity extends AppCompatActivity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
 
        //back 버튼
        ActionBar actionBar = this.getSupportActionBar();
        if(actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        //홈 버튼이 눌러졌을 때 뒤로 돌아가게 함
        if(id == R.id.home) {
            NavUtils.navigateUpFromSameTask(this);
        }
        return super.onOptionsItemSelected(item);
    }
}
 
cs




Android Course of Udacity - Lesson 6

Data Persistence


영속적인 데이터는 핸드폰에 데이터를 저장하는 것을 말한다.



5가지 데이터 영속 방식


1. onSavedInstanceState


뷰의 상태에 키-값 쌍을 저장한다.

앱의 화면 회전하거나 또는 액티비티가 메모리 부족으로 다운되었을 때 상태를 저장하기 위해 쓰인다.

앱의 상태를 저장하기 위한 일시적인 방법이다.

앱을 계속 사용중일 때만 사용할 수 있다.

앱을 종료하거나 새로 시작 시 저장된 데이터는 사라진다.



2. SharedPreferences


하나의 파일 안에 간단한 키-값 쌍을 저장한다.

키값은 항상 string 이어야 하고, value는 primitive (boolean, string 등) 이여야 한다.

사용자에 대한 간단한 문장이나 숫자값을 저장하기 위해 이용된다.

(예-사용자 이름, 사용자가 보고 있던 페이지에 대한 정보)



3. SQLite Database


복잡한 데이터를 저장할 때 사용한다.



4. Internal / External storage


멀티미디어나 더 큰 데이터를 저장할 때 사용한다.



5. Server


여러 종류의 디바이스에서 접속된 데이터를 저장할 때 사용한다.

핸드폰에 저장하는 것이 아닌 cloud에 저장하는 것이며,

이는 서버에 DB를 저장하거나 Firebase 같은 서비스를 사용하는 것을 의미한다.




Preference Fragments


SharedPreferences는 앱의 Preference를 저장하기 때문에 'Shared' Preferences라 불린다.


앱의 환경설정에 사용되기 때문에 세팅 액티비티를 만드는 것처럼

다른 안드로이드의 프레임워크와 협업이 필요하다.


Fragment란 모듈 단위의 재사용이 가능한 액티비티의 한 부분 클래스를 말한다.


Preference Fragment는 XML에 정의된 Preferences을 저장하고 있다.

액티비티 레이아웃을 XML에 정의할 때와 똑같은 방식이다.


Fragment 안의 UI 위젯들을 만들 때 사용되며,

위젯의 값을 변경하게 되면 관련된 키-값 쌍을 SharedPreference 파일에서 변경해준다.




Android Course of Udacity - Lesson 6


+ Recent posts