2022 Aug. 13.
MainActivity.kt
class MainActivity : AppCompatActivity() { val binding: ActivityMainBinding by lazy {ActivityMainBinding.inflate(layoutInflater)} override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) val myViewModel: MyViewModel by viewModels() myViewModel._myString.value = "Hello" val myStringObserver = Observer<String> { it -> binding.textView01.text = it } myViewModel.myString.observe(this, myStringObserver) } }
MyViewModel.kt
class MyViewModel: ViewModel() { val _myString = MutableLiveData<String>("") val myString: LiveData<String> get() = _myString }