Bmi ์ฑ ๋ฉ๋ชจ
์ด์ ํ๋ฉด์ผ๋ก ๋์๊ฐ๋ ์ ๋ค๋น๊ฒ์ด์
startActivity๋ฅผ ํ์ฉํ์ฌ ์๋ก์ด ์กํฐ๋นํฐ๋ฅผ ๋์ ์ ๋ ๋ค๋ก๊ฐ๊ธฐ ๋ฒํผ์ ํ์ฉํ์ฌ ์ด์ ์กํฐ๋นํฐ๋ก ๋์๊ฐ ์๋ ์๋ค.
ํ์ง๋ง ์ฌ์ฉ์๊ฐ ์ด์ ํ๋ฉด์ผ๋ก ๋์๊ฐ ์ ์๋ค๋ ๊ฒ์ ์์์ฑ ์ ์๋ ๋จ์๋ ํ๋ฉด ์ด๋์๋ ์๋ค.
์ ๋ค๋น๊ฒ์ด์ ์ ๋ง๋ค๋ฉด ์๋จ์ ์ด์ ํ๋ฉด์ผ๋ก ๋์๊ฐ๊ธฐ ์ํ ํ์ดํ๋ฅผ ๋ง๋ค ์ ์๋ค.
ํ๋ก์ ํธ์ manifest ํด๋ ๋ด์ xmlํ์ผ์ ์ด์.
ํ๋ก์ ํธ์ ์์ฑ๋ ๋ชจ๋ ์กํฐ๋นํฐ๊ฐ ์กํฐ๋นํฐ ํ๊ทธ๋ก ๋ง๋ค์ด์ ธ ์์ ๊ฒ์ด๋ค.
์ฌ๊ธฐ์ ๋ค๋ก๊ฐ๊ธฐ ๋ฒํผ์ ํ์ํ ์กํฐ๋นํฐ๋ฅผ, ๋ค๋ก๊ฐ์๋ ๋ณด์ผ ์กํฐ๋นํฐ์ ์์์ผ๋ก ์ค์ ํด์ฃผ๋ฉด ๋๋ค.
<activity
android:name=".ResultActivity"
android:exported="false"
android:parentActivityName=".MainActivity"/>
์์ ์ฝ๋์์๋ ResultActivity์ ๋ถ๋ชจ Activity๋ก MainActivity๋ฅผ ์ค์ ํด ์ฃผ์๋ค.
์ด๋ ๊ฒ ๊ฐ๋จํ๊ฒ ์กํฐ๋นํฐ๊ฐ์ ์ํ๊ด๊ณ๋ฅผ ์ ํด์ค ์ ์๋ค.
์ธํ ํธ์ ๋ฐ์ดํฐ ๋ด๊ธฐ
์ธํ ํธ์ ๋์ดํฐ๋ฅผ ๋ด์ ์ ๋ฌํ๊ณ ์ถ๋ค๋ฉด ์ธํ ํธ ๋ณ์์ putExtra ๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ฉด ๋๋ค.
val intent = Intent(this, ResultActivity::class.java)
intent.putExtra("weight", weightEditText.text.toString())
intent.putExtra("height", heightEditText.text.toString())
startActivity(intent)
putExtra(์ ๋ฌํ ๋ฐ์ดํฐ์ ์ด๋ฆ, ๋ฐ์ดํฐ) ์ ํ์์ผ๋ก ์ ๋ฌํด์ฃผ๋ฉด ๋๋ค.
๋ฐ์ดํฐ๋ฅผ ๊บผ๋ผ ๋์๋
์ธํ
ํธ๋ณ์.get์๋ฃํExtra(์ ๋ฌ๋ฐ์๋ฐ์ดํฐ์ด๋ฆ)
์ ๋ฐฉ์์ผ๋ก ๋ฐ์ดํฐ๋ฅผ ๊บผ๋ผ ์ ์๋ค.
์์ ์์ ์ฌ์ฉํ ์ฝ๋๋ ๋ค์๊ณผ ๊ฐ๋ค.
val height = intent.getStringExtra("height")?.toInt()
val weight = intent.getStringExtra("weight")?.toInt()
๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๊ณ ๊บผ๋ด๊ธฐ
์ฑ์ด ์ข ๋ฃ๋์ด๋ ๋ฐ์ดํฐ๊ฐ ์ ์ฅ๋์ด ๋ณด๊ด๋๋๋ก ํ๋ ๋ฐฉ๋ฒ์ ์์๋ณด์.
Bmi์ฑ์ MainActivity.kt ์ ๋ฉ์๋๋ก ๋ง๋ ๋ฐ์ดํฐ ์ ์ฅ ์ฝ๋๋ ๋ค์๊ณผ ๊ฐ๋ค.
private fun saveData(height: Int, weight: Int){
val pref = PreferenceManager.getDefaultSharedPreferences(this)
val editor = pref.edit()
editor.putInt("KEY_HEIGHT", height)
.putInt("KEY_WEIGHT", weight)
.apply()
}
preference ๊ฐ์ฒด๋ฅผ ๋ฐ์ ์ ์ฅํ๊ณ , ๊ทธ ๊ฐ์ฒด์ edit ๋ฉ์๋๋ฅผ ๋ณ์(editor)์ ์ ์ฅํ๋ค.
editor ์ putInt ๋ฉ์๋์ ๋ฐ์ดํฐ ์ด๋ฆ๊ณผ ๋ฐ์ดํฐ๊ฐ์ ์ ๋ฌํ์ฌ ์ ์ฅํ๊ณ apply ๋ฉ์๋๋ก ์ ์ฅํด์ฃผ๋ฉด ๋ฐ์ดํฐ๊ฐ ์ ์ฅ๋๋ค.
๋ค์์ผ๋ก ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์ค๋ ๋ฉ์๋๋ฅผ ์ดํด๋ณด์.
private fun loadData() {
val pref = PreferenceManager.getDefaultSharedPreferences(this)
val height = pref.getInt("KEY_HEIGHT", 0)
val weight = pref.getInt("KEY_WEIGHT", 0)
if (height != 0 && weight != 0) {
heightEditText.setText(height.toString())
weightEditText.setText(weight.toString())
}
}
๋์ผํ๊ฒ preference ๊ฐ์ฒด๋ฅผ ๋ฐ์ ์ ์ฅํ ๋ค์, ๊ฐ์ฒด์ get์๋ฃํ ๋ฉ์๋๋ฅผ ํตํด ์ ์ฅ๋ ๊ฐ์ ๋ฐ์์จ๋ค.
๋ถ๋ฌ์ฌ ๋ฐ์ดํฐ ์ด๋ฆ๊ณผ ํจ๊ป ์ ๋ฌ๋๋ ์ธ์๋ ์ ์ฅ๋ ๋ฐ์ดํฐ๊ฐ ์์ ๊ฒฝ์ฐ ๊ฐ์ ธ์ฌ default ๊ฐ์ด๋ค.
์ดํ ์ ์ ํ ๊ฐ๋ค์ returnํ ์๋ ์๊ณ , ์์ ์ฝ๋์ฒ๋ผ ๋ฐ๋ก ํ์ฉํ ์๋ ์๋ค.