안녕하세요! 여러분들 오늘은 SharedPreference에 대해 알아보아요

간단한 로그인 기능을 구현해볼 것입니다.

 

1) 프로젝트를 생성합니다.

empty 설정 해주세요

 

2) xml 코드를 작성합니다.

코드를 작성하다가 android:onClick="erase" 에서는 붉은 줄이 생길 텐데요,

그러면 alt + enter 키로 자바 폴더에 생성하기 를 하시면 간단하게 

터치 기능을 사용할 수 있습니다.

 

 

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
<?xml version="1.0" encoding="utf-8"?>
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
 
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="60dp"
        android:layout_marginEnd="32dp"
        android:layout_marginRight="32dp"
        android:layout_marginBottom="32dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
 
 
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="로그인"
            android:textStyle="bold"
            android:gravity="center"
            android:textSize="25sp"/>
 
        <EditText
            android:layout_marginTop="30dp"
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="ID 입력"
            android:inputType="textPersonName" />
 
        <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="비밀번호 입력"
            android:inputType="textPersonName" />
 
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
 
            <Button
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="erase"
                android:text="지우기" />
 
            <Button
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="confirm"
                android:text="로그인" />
 
        </LinearLayout>
 
        <CheckBox
            android:layout_marginTop="10dp"
            android:id="@+id/checkBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="아이디 저장하기"
            />
 
    </LinearLayout>
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

 

따라 해 보시면 위의 이미지와 같이 됩니다. 

위의 이미지를 보면 아이디 저장하기라는 체크 박스가 있습니다.

체크가 된 상태인지 onStop메서드가 호출될 때 확인할 것이며

체크가 되었다면 sharedPreference를 사용하여 File이라는

파일에 아이디를 저장해 둘 것입니다. 

 

3) 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
package com.example.test_sharedpreference;
 
import android.content.SharedPreferences;
 
 
public class MainActivity extends AppCompatActivity {
 
    private EditText editText1;
    private EditText editText2;
    private CheckBox checkBox;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editText1 = findViewById(R.id.editText);
        editText2 = findViewById(R.id.editText2);
        checkBox = findViewById(R.id.checkBox);
 
        //File이란 파일로 저장해둔 값을 가져오기위한 설정
        SharedPreferences sf = getSharedPreferences("File",MODE_PRIVATE);
        //text1에 값이 있으면 가져오고 두번째 인자는 없을경우 가져오는 값이다.
        String text1 = sf.getString("text1","");
 
        // text!가 그냥 공백이 아니라면 아이디 저장이된 상태이기 때문에 체크박스를
        // 체크 상태로 변환한다.
        if(!(text1.equals("")))
            checkBox.setChecked(true);
 
        editText1.setText(text1);
 
 
    }
 
    public void erase(View view) {
        editText1.setText("");
        editText2.setText("");
    }
 
    public void confirm(View view) {
 
    }
 
    @Override
    protected void onStop() {
        super.onStop();
 
        SharedPreferences sharedPreferences = getSharedPreferences("File",MODE_PRIVATE);
        //저장을 하기위해 editor를 이용하여 값을 저장시켜준다.
 
        //체크 박스에 체크가 됬다면 아이디를 저장한다.
        if(checkBox.isChecked()) {
            String text1 = editText1.getText().toString();
            editor.putString("text1", text1);
        }
        else
        {
            editor.putString("text1""");
        }
 
        // 값을 다 넣었으면 commit으로 완료한다.
        editor.commit();
    }
}
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

이상으로 sharedPreference를 사용해 보았습니다. 

혹시 궁금한 것이 있다면 댓글로 남겨주세요 

 

소스코드는 깃허브에 있습니다.

https://github.com/3210439/test_sharedPreference

 

3210439/test_sharedPreference

Contribute to 3210439/test_sharedPreference development by creating an account on GitHub.

github.com

 

 

1) 프래그먼트 패키지 생성

 

프래그먼트를 보관할 패키지를 자바 폴더에 있는 com.example. 프로젝트명 파일에 생성한다

 

 

2) 프래그먼트 생성

블랭크 프래그먼트 3개를 방금 생성한 패키지에 생성한다 

주의 사항 

Include factory methods? 선택 해체

Include interface callbacks? 선택 해체

 

 

 

3)material 임포트 하기

projectStructure를 켠다

Ctrl+Shift+alt+s 단축키

 

1. 왼쪽 메뉴에서 Dependencies를 선택한다 

2. all Dependencies 아래 + 마크를 클릭한다

3. Library Dependancy를 클릭한다

 

material이라는 키워드로 검색 후

com.google.android.material을 선택하고

버전은 최신 버전을 선택한다

 

projectStructure의 장점은

빠르게 변화하는 안드로이드 메소드 덕분에

구 버전을 사용하면 생기는

오류들로부터 자유로울 수 있다

 

 

4) 메인 액티비티 레이아웃에 탭 레이아웃 추가

 

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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabMode="fixed"
        app:tabTextColor="#ffffff"
        app:tabSelectedTextColor="#ffffff"
        android:background="@color/colorPrimaryDark"
        />
 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/view_pager"
/>
 
</LinearLayout>
 
 

 

ConstraintLayout을 Linearlayout  방향 vertical

로 변경하고 탭 레이아웃과 뷰 페이저를 추가한다.

여기서 뷰 페이저의 역할은

프래그먼트들을 가로로 이어 붙여주고

탭 레이아웃에서 선택하면

선택된 프래그먼트로 이동하는데 부드럽게 넘어가는 모션이

추가된다 축측하고 있습니다.

 

이어서 자바 파일에 

탭 레이아웃과 뷰 페이저를 선언한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.example.test_tablayout;
 
 
 
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        TabLayout tabLayout = findViewById(R.id.tab_layout);
        ViewPager viewPager = findViewById(R.id.view_pager);
    }
}
 
 
 

 

 

 

이어서 자바 폴더에 뷰 페이저 어뎁터 클래스를 생성한다.

 

extends FragmentPagerAdapter 부모 클래스를 추가한다.

재목에 빨간 줄이 생기는데, Alt+Enter를 클릭하면

필요한 메서드들을 자동적으로 추가하는 기능이 있다.

나머지는 밑의 코드를 참고하여 추가하면된다.

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
package com.example.test_tablayout;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
 
 
public class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> fragmentList = new ArrayList<>();
    private final List<String> fragmentListTitle = new ArrayList<>();
 
    public ViewPagerAdapter(@NonNull FragmentManager fm) {
        super(fm);
    }
 
    @NonNull
    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }
 
    @Override
    public int getCount() {
        return fragmentListTitle.size();
    }
 
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentListTitle.get(position);
    }
 
    public void AddFragment(Fragment fragment, String Title){
        fragmentList.add(fragment);
        fragmentListTitle.add(Title);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

AddFragment는 뷰 페이저에 프래그먼트와 이름을 같이 추가하기 위해 생성된 메서드이다.

 

 

5) 자바 코드로 돌아와서 뷰 페이저 어뎁터 설정을 해준다.

 

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
package com.example.test_tablayout;
 
 
 
import com.example.test_tablayout.Fragments.BlankFragment;
import com.example.test_tablayout.Fragments.BlankFragment2;
import com.example.test_tablayout.Fragments.BlankFragment3;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        TabLayout tabLayout = findViewById(R.id.tab_layout);
        ViewPager viewPager = findViewById(R.id.view_pager);
        
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.AddFragment(new BlankFragment(), "First Fmt");
        viewPagerAdapter.AddFragment(new BlankFragment2(), "Second Fmt");
        viewPagerAdapter.AddFragment(new BlankFragment3(), "Third Fmt");
        
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
 
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

뷰 페이저 어뎁터를 생성하고

프래그먼트와 타이틀 정보를 입력한다.

 

그리고 뷰 페이저에 뷰페이저 어댑터를 넣는다.

그리고 탭 레이아웃에 뷰 페이저를 넣는다.

 

6) 프레그먼트들의 레이아웃에 자기 이름 입력

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragments.BlankFragment">
 
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="fragment1" />
 
</FrameLayout>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

나머지 2와 3도 설정하십시오

 

결과 확인

 

소스코드는 깃허브에 있습니다.

https://github.com/3210439/test_tablayout

 

3210439/test_tablayout

Contribute to 3210439/test_tablayout development by creating an account on GitHub.

github.com

 

참조한 자료

https://youtu.be/PJWBnkWudEI

 

1) 프로젝트 생성

 

 

2) res> menu directory 생성

 

 

3) menu 폴더에 xml 파일 생성

 

4) 메뉴 xml 파일 코드 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    <item
        android:title="첫 번째"
        android:icon="@drawable/ic_launcher_background"
        android:id="@+id/first_opt"/>
    <item
        android:title="두 번째"
        android:icon="@drawable/ic_launcher_background"
        android:id="@+id/second_opt"/>
    <item
        android:title="세 번째"
        android:icon="@drawable/ic_launcher_background"
        android:id="@+id/third_opt"/>
</menu>
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

여기서 아이템 설정에 android:showAsAction="ifRoom" 을 하게 되면 

만약, 툴바(앱바)에 아이콘이 표시될 공간이 있다면 표시해주게 된다.

 

onCreateOptionsMenu 오버라이드 하기

1
2
3
4
5
6
7
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mymenu,menu);
        return true;
    }
 

 

inflater를 통해 메뉴를 풍선에 바람 넣어 형태를 만들듯 툴바에 메뉴 아이콘이 생기고

클릭하게 되면 메뉴가 표시된다.

 

 

6) onOptionsItemSelected

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.first_opt:
                Toast.makeText(getApplicationContext(), "첫번째", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.second_opt:
                Toast.makeText(getApplicationContext(), "두번째", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.third_opt:
                Toast.makeText(getApplicationContext(), "새번째", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
   }

 

결과 확인

 

 

아이템을 클릭하게 되면 토스트 메시지가 출력되게 된다.

 

 

 

소스코드는 깃허브에서 다운 가능합니다.

https://github.com/3210439/toolbar_test

 

3210439/toolbar_test

Contribute to 3210439/toolbar_test development by creating an account on GitHub.

github.com

 

+ Recent posts