onCreate() -> onStart() -> onResume() -> Activity running -> onPause() -> onStop() -> onDestroy() -> Activity shut down
package kit.ac.kr.s20200607.kolin_lifecycle
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.i("Lifecycle", "onCreate()")
}
override fun onStart() {
super.onStart()
Log.i("Lifecycle", "onStart()")
}
override fun onStop() {
super.onStop()
Log.i("Lifecycle", "onStop()")
}
override fun onDestroy() {
super.onDestroy()
Log.i("Lifecycle", "onDestroy()")
}
override fun onResume() {
super.onResume()
Log.i("Lifecycle", "onResume()")
}
override fun onRestart() {
super.onRestart()
Log.i("Lifecycle", "onRestart()")
}
override fun onPause() {
super.onPause()
Log.i("Lifecycle", "onPause()")
}
}
savedInstanceState
저장된 인스턴스의 상태android:layout_margin="16dp" //부모랑 관련있어서 layout_붙음
padding은 안 붙음 - 자기 안에서만 적용되니까
- snake case: 소문자 + 언더바 - xml (btn_add)
- pascal case (upperCamel case): 맨 첫 글자 대문자 (BtnAdd)
- camel case: 맨 앞 글자 소문자 → binding하면 자동 바뀜 (btnAdd)
// 화면 회전 시 초기화 방지
package kit.ac.kr.s20200607.kolin_lifecycle
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import kit.ac.kr.s20200607.kolin_lifecycle.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
// var count = 0
private val model: CounterViewModel byviewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
//setContentView(R.layout.activity_main)
setContentView(binding.root)
binding.txtCount.text= model.count.toString()
binding.btnAdd.setOnClickListener{
model.add()
binding.txtCount.text= model.count.toString()
}
}
}
package kit.ac.kr.s20200607.kolin_lifecycle
import androidx.lifecycle.ViewModel
//encapsulation 적용
class CounterViewModel:ViewModel() {
private var _count = 0
var count
get() = _count
set(value){
_count = value
}
fun add() {
_count++
}
}
private var _count = MutableLiveData<Int>(0)
private var _count = MutableLiveData<Int>(0)
val count: LiveData<Int>
get() = _count
fun add() {
_count.value?.plus(1)
}
깔끔하게 정리해주셔서 감사합니다.