Android Application
Kotlin 파일처리 : 간단 일기장 앱 만들기
작성자 임베디드코리아
작성일 23-10-16 22:38
조회1,656회
댓글0건
Kotlin 파일처리 : 간단 일기장 앱 만들기
-------------------------------------------------------------------------------------
activity_main.xml
-------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<DatePicker
android:datePickerMode="spinner"
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:calendarViewShown="false" />
<EditText
android:layout_weight="1"
android:id="@+id/edtDiary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00ff00"
android:lines="8" >
</EditText>
<Button
android:id="@+id/btnWrite"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:text="Button" />
</LinearLayout>
------------------------------------------------------------------------------------
MainActivity.kt
------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
lateinit var dp: DatePicker
lateinit var edtDiary: EditText
lateinit var btnWrite: Button
lateinit var fileName: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dp = findViewById<DatePicker>(R.id.datePicker1)
edtDiary = findViewById<EditText>(R.id.edtDiary)
btnWrite = findViewById<Button>(R.id.btnWrite)
var cal = Calendar.getInstance()
var cYear = cal.get(Calendar.YEAR)
var cMonth = cal.get(Calendar.MONTH)
var cDay = cal.get(Calendar.DAY_OF_MONTH)
dp.init(cYear, cMonth, cDay) { view, year, monthOfYear, dayOfMonth ->
fileName = (Integer.toString(year) + "_"
+ Integer.toString(monthOfYear + 1) + "_"
+ Integer.toString(dayOfMonth) + ".txt")
var str = readDiary(fileName)
edtDiary.setText(str)
btnWrite.isEnabled = true
}
btnWrite.setOnClickListener {
var outFs = openFileOutput(fileName, Context.MODE_PRIVATE)
var str = edtDiary.text.toString()
outFs.write(str.toByteArray())
outFs.close()
Toast.makeText(applicationContext, "$fileName 이 저장됨", Toast.LENGTH_SHORT).show()
}
}
fun readDiary(fName: String) : String? {
var diaryStr : String? = null
var inFs : FileInputStream
try {
inFs = openFileInput(fName)
var txt = ByteArray(500)
inFs.read(txt)
inFs.close()
diaryStr = txt.toString(Charsets.UTF_8).trim()
btnWrite.text = "수정 하기"
} catch (e : IOException) {
edtDiary.hint = "일기 없음"
btnWrite.text = "새로 저장"
}
return diaryStr
}
}
158-840 서울시 양천구 남부순환로 571(신월동, 영남타운 307호) l 대표: 박길성 ㅣ Tel:02-2695-1114 ㅣ Fax:02-2695-1113
Copyright © 2015 Embedded Korea. All Rights Reserved.