불로구

안드로이드 스튜디오 - 다이어리 만들기 본문

프로그래밍/코틀린 안드로이드

안드로이드 스튜디오 - 다이어리 만들기

맹이맹이 2021. 3. 28. 02:14
반응형

 

MainActivity.kt

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.NumberPicker
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.AppCompatButton
import androidx.core.content.edit

class MainActivity : AppCompatActivity() {
    private val numberPicker1 : NumberPicker by lazy {
        findViewById<NumberPicker>(R.id.numberPicker1)
            .apply{
                minValue = 0
                maxValue = 9
            }
    }
    private val numberPicker2 : NumberPicker by lazy {
        findViewById<NumberPicker>(R.id.numberPicker2)
            .apply{
                minValue = 0
                maxValue = 9
            }
    }
    private val numberPicker3 : NumberPicker by lazy {
        findViewById<NumberPicker>(R.id.numberPicker3)
            .apply{
                minValue = 0
                maxValue = 9
            }
    }

    private val openButton : AppCompatButton by lazy{
        findViewById<AppCompatButton>(R.id.openButton)
    }
    private val changePasswordButton : AppCompatButton by lazy{
        findViewById<AppCompatButton>(R.id.changePasswordButton)
    }
    private var changePasswordMode = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //view는 onCreate이후 그려지기 때문에 호출해주지 않으면 min, max 설정한 값이 할당되지 않음
        numberPicker1
        numberPicker2
        numberPicker3

        openButton.setOnClickListener {
            if(changePasswordMode){
                Toast.makeText(this,"비밀번호 변경중인 상태", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val passwordPreferences:SharedPreferences = getSharedPreferences("password", Context.MODE_PRIVATE) //나만 사용할 수 있도록 MODE_PRIVATE
            val passwordFromUser : String = "${numberPicker1.value}${numberPicker2.value}${numberPicker3.value}"
            if(passwordPreferences.getString("password", "000").equals(passwordFromUser)){ //초기 패스워드
                //TODO 다이어리 페이지 작성 후 넘겨줌
                startActivity(Intent(this, DiaryActivity::class.java))
            }else{
                showErrorAlertDialog()
            }
        }

        changePasswordButton.setOnClickListener {
            val passwordPreferences:SharedPreferences = getSharedPreferences("password", Context.MODE_PRIVATE)
            val passwordFromUser : String = "${numberPicker1.value}${numberPicker2.value}${numberPicker3.value}"
            if(changePasswordMode){ // true면 저장
                passwordPreferences.edit{
                    putString("password", passwordFromUser)
                    //저장에는 2개 방법이 있음 -> commit - > 다 저장까지 ui 정지, apply -> 비동기적으로 저장
                }

                changePasswordMode = false
                changePasswordButton.setBackgroundColor(Color.BLACK)

            }else{ //false면 changepasswordMode 활성화 -> 비밀번호 맞는지 체크
                if(passwordPreferences.getString("password", "000").equals(passwordFromUser)){ //초기 패스워드
                    changePasswordMode = true
                    Toast.makeText(this, "변경할 패스워드 입력", Toast.LENGTH_SHORT).show()
                    changePasswordButton.setBackgroundColor(Color.RED)
                }else{
                   showErrorAlertDialog()
                }
            }
        }
    }
    private fun showErrorAlertDialog(){
        AlertDialog.Builder(this)
            .setTitle("실패")
            .setMessage("비밀번호가 다릅니다.")
            .setPositiveButton("확인") { _ , _ -> } //dialog, which 변수를 사용하지 않기 때문에 언더바로 처리
            .create()
            .show()
    }

}

DiaryActivity.kt


import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.core.widget.addTextChangedListener

class DiaryActivity : AppCompatActivity() {
    private val diaryEditText : EditText by lazy { findViewById<EditText>(R.id.diaryEditText) }
    private val handler = Handler(Looper.getMainLooper()) //메인스레드에 연결된 핸들러 생성
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_diary)

        val detailPreferences = getSharedPreferences("diary", Context.MODE_PRIVATE)

        diaryEditText.setText(detailPreferences.getString("detail", ""))

        //특정 상태에 저장되게 구현
        val runnable = Runnable {
            getSharedPreferences("diary", Context.MODE_PRIVATE).edit{
                putString("detail", diaryEditText.text.toString())
            }
            Log.d("DiaryActivity", "Save!!")
        }

        diaryEditText.addTextChangedListener {

            //이렇게만 사용하면 한글자씩 계속 저장됨
            //detailPreferences.edit{
            //putString("detail", diaryEditText.text.toString())
            //}
            Log.d("DiaryActivity", "TextChanged :: $it")
            //0.5이전에 아직 실행되지 않고 펜딩되어있는 runnable이 있다면 지우기 위한 작업
            handler.removeCallbacks(runnable)
            //0.5초이후 스레드 실행
            handler.postDelayed(runnable, 500)
        }

    }
}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    android:background="#454545"
    tools:context=".MainActivity">

    <TextView
        app:layout_constraintBottom_toTopOf="@id/passwordLayout"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:text="나의 비밀 노트"
        android:layout_marginBottom="10dp"
        android:textSize="30sp"
        android:textStyle="bold"
        android:fontFamily="@font/custom_font"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/passwordLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#CDCDCD"
        android:padding="15dp"
        app:layout_constraintVertical_bias="0.45"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/openButton"
            android:layout_width="40dp"
            android:layout_height="60dp"
            android:layout_marginEnd="10dp"
            android:background="#A3A3A3"
            app:layout_constraintBottom_toBottomOf="@id/numberPicker1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@id/numberPicker1"
            app:layout_constraintTop_toTopOf="@id/numberPicker1" />

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/changePasswordButton"
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:layout_marginTop="10dp"
            android:background="@color/black"
            app:layout_constraintEnd_toEndOf="@id/openButton"
            app:layout_constraintStart_toStartOf="@id/openButton"
            app:layout_constraintTop_toBottomOf="@id/openButton" />

        <NumberPicker
            android:id="@+id/numberPicker1"
            android:layout_width="30dp"
            android:layout_height="120dp"
            android:background="#A3A3A3"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@id/numberPicker2"
            app:layout_constraintHorizontal_chainStyle="packed"
            app:layout_constraintStart_toEndOf="@id/openButton"
            app:layout_constraintTop_toTopOf="parent" />

        <NumberPicker
            android:id="@+id/numberPicker2"
            android:layout_width="30dp"
            android:layout_height="120dp"
            android:background="#A3A3A3"
            app:layout_constraintEnd_toStartOf="@id/numberPicker3"
            app:layout_constraintStart_toEndOf="@id/numberPicker1"
            app:layout_constraintTop_toTopOf="@id/numberPicker1" />

        <NumberPicker
            android:id="@+id/numberPicker3"
            android:layout_width="30dp"
            android:layout_height="120dp"
            android:background="#A3A3A3"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/numberPicker2"
            app:layout_constraintTop_toTopOf="@id/numberPicker1" />


    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

 

activity_diary.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="24dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#454545">
    <EditText
        android:id="@+id/diaryEditText"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@color/white"
        android:padding="10dp"
        android:gravity="start|top"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        />

</androidx.constraintlayout.widget.ConstraintLayout>
반응형
Comments