Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

CPP-Shooter's Life

안드로이드 메모장 앱 만들기 본문

Programming/Android

안드로이드 메모장 앱 만들기

CPP-Shooter 2019. 1. 21. 18:47

안드로이드 앱 기초 공부의 일환으로 메모장 앱을 만들어보았다.

버튼을 통해 텍스트파일을 저장,로드,삭제하는 기능을 구현하고

에디트 텍스트 (Edit Text) UI를 통해 메모 텍스트를 멀티라인 입력할 수 있게 하였다.


구현한 메인 액티비티와 레이아웃 소스는 아래와 같다.


개발 환경 : Android Studio 3.3

               minSdkVersion : 21 (Lolipop)

               targetSdkVersion, compileSdkVersion : 27 (Oreo)


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
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">
 
    <Button
        android:id="@+id/button_load"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="33dp"
        android:layout_marginBottom="13dp"
        android:text="메모 로드"
        app:layout_constraintBottom_toTopOf="@+id/editText3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />
 
    <Button
        android:id="@+id/button_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:text="메모 저장"
        app:layout_constraintStart_toEndOf="@+id/button_load"
        app:layout_constraintTop_toTopOf="parent" />
 
    <EditText
        android:id="@+id/editText3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:ems="10"
        android:gravity="top"
        android:inputType="textMultiLine"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_load" />
 
    <Button
        android:id="@+id/button_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="메모 삭제"
        app:layout_constraintBaseline_toBaselineOf="@+id/button_save"
        app:layout_constraintStart_toEndOf="@+id/button_save" />
 
</android.support.constraint.ConstraintLayout>
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package com.example.seonju_notepad;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
 
public class MainActivity extends AppCompatActivity {
 
    //버튼 객체
    private Button btn_Save;
    private Button btn_Load;
    private Button btn_Delete;
    //에디트 박스 객체
    private EditText editText_TextArea;
    //메모를 저장할 파일명 (파일 하나만 지원)
    private String fileName = "MyMemo.txt";
    //백버튼 누른 시간 저장
    private long backPressTime = 0;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //버튼, 에디트박스 객체 가져오기
        btn_Save = findViewById(R.id.button_save);
        btn_Load = findViewById(R.id.button_load);
        btn_Delete = findViewById(R.id.button_delete);
        editText_TextArea = findViewById(R.id.editText3);
 
        //버튼 객체에 클릭 리스너 함수 등록
        btn_Save.setOnClickListener(btnSaveListener);
        btn_Load.setOnClickListener(btnLoadListener);
        btn_Delete.setOnClickListener(btnDeleteListener);
    }
 
    //파일 로드 버튼 클릭처리
    View.OnClickListener btnLoadListener = new View.OnClickListener()
    {
        //새로 생성할 리스너에 할당할 onClick 함수 구현
        public void onClick(View v)
        {
            //Toast.makeText(getApplicationContext(), "로드 버튼 클릭 테스트", Toast.LENGTH_LONG).show();
            //파일 로드 시 이용할 파일 입력 스트림
            FileInputStream inputStream = null;
 
            try
            {
                inputStream = openFileInput(fileName);
                //바이트 단위로 스트림 데이터를 읽음
                byte[] data = new byte[inputStream.available()];
                while(inputStream.read(data) != -1) {}
 
                //현재 에디트 박스에 읽은 바이트 데이터를 세팅
                editText_TextArea.setText(new String(data));
                //화면 아래 간단한 알림 메시지 출력
                Toast.makeText(getApplicationContext(), "로드 성공", Toast.LENGTH_LONG).show();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                try
                {
                    //파일 읽기 성공 여부 상관없이 반드시 스트림 닫기
                    if(inputStream != null)
                        inputStream.close();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    };
 
    //파일 저장 버튼 클릭처리
    View.OnClickListener btnSaveListener = new View.OnClickListener()
    {
        public void onClick(View v)
        {
            //Toast.makeText(getApplicationContext(), "저장 버튼 클릭 테스트", Toast.LENGTH_LONG).show();
            //파일 저장 시 이용할 파일 출력 스트림
            FileOutputStream outputStream = null;
 
            try
            {
                outputStream = openFileOutput(fileName, MODE_PRIVATE);
                //에디트 박스에 저장된 스트링 데이터를 스트림에 기록함
                outputStream.write(editText_TextArea.getText().toString().getBytes());
                outputStream.close();
 
                Toast.makeText(getApplicationContext(), "저장 성공", Toast.LENGTH_LONG).show();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    };
 
    //파일 삭제 버튼 클릭처리
    View.OnClickListener btnDeleteListener = new View.OnClickListener()
    {
        public void onClick(View v)
        {
            //Toast.makeText(getApplicationContext(), "삭제 버튼 클릭 테스트", Toast.LENGTH_LONG).show();
            //해당 파일을 디스크 상에서 삭제, true 리턴 시 삭제 성공
            boolean bDel = deleteFile(fileName);
            if(bDel)
                Toast.makeText(getApplicationContext(), "메모 삭제 완료", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(getApplicationContext(), "메모 삭제 실패", Toast.LENGTH_LONG).show();
        }
    };
 
    //백버튼 두번 연속 입력으로 종료 처리
    @Override
    public void onBackPressed()
    {
        if(System.currentTimeMillis() - backPressTime >= 2000)
        {
            backPressTime = System.currentTimeMillis();
            Toast.makeText(getApplicationContext(), "백(Back) 버튼을 한 번 더 누르면 종료", Toast.LENGTH_LONG).show();
        }
        else if(System.currentTimeMillis() - backPressTime < 2000)
            finish();
    }
}
 
cs