「Android/kotlin/LiveData」の版間の差分
提供: 初心者エンジニアの簡易メモ
(ページの作成:「==LiveDataとは== activityなどでデータを保管するのではなく、modelなどに保管するもの。 ==サンプル== app/build.gradle <pre> dependencies {...」) |
|||
| 行12: | 行12: | ||
</pre> | </pre> | ||
| + | MainActivity.kt | ||
| + | <pre> | ||
| + | import androidx.appcompat.app.AppCompatActivity | ||
| + | import android.os.Bundle | ||
| + | import androidx.lifecycle.Observer | ||
| + | |||
| + | class MainActivity : AppCompatActivity() { | ||
| + | override fun onCreate(savedInstanceState: Bundle?) { | ||
| + | super.onCreate(savedInstanceState) | ||
| + | setContentView(R.layout.activity_main) | ||
| + | var hogeViewModel = HogeViewModel() | ||
| + | hogeViewModel.hoge.observe(this, Observer { it -> | ||
| + | var hoge = it | ||
| + | println("hoge=$hoge") | ||
| + | }) | ||
| + | hogeViewModel.changeHoge() | ||
| + | } | ||
| + | } | ||
| + | </pre> | ||
| + | |||
| + | HogeViewModel.kt | ||
| + | <pre> | ||
| + | import androidx.lifecycle.LiveData | ||
| + | import androidx.lifecycle.MutableLiveData | ||
| + | import androidx.lifecycle.ViewModel | ||
| + | |||
| + | class HogeViewModel : ViewModel() { | ||
| + | private var _hoge: MutableLiveData<String> | ||
| + | var hoge: LiveData<String> | ||
| + | init { | ||
| + | _hoge = MutableLiveData<String>() | ||
| + | hoge = _hoge | ||
| + | } | ||
| + | |||
| + | fun changeHoge() { | ||
| + | _hoge.value = "test" | ||
| + | } | ||
| + | } | ||
| + | </pre> | ||
参考:https://qiita.com/K4N4/items/17012d5a1ffcc6fe9681 | 参考:https://qiita.com/K4N4/items/17012d5a1ffcc6fe9681 | ||
2021年2月10日 (水) 14:50時点における版
LiveDataとは
activityなどでデータを保管するのではなく、modelなどに保管するもの。
サンプル
app/build.gradle
dependencies {
def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
}
MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.Observer
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var hogeViewModel = HogeViewModel()
hogeViewModel.hoge.observe(this, Observer { it ->
var hoge = it
println("hoge=$hoge")
})
hogeViewModel.changeHoge()
}
}
HogeViewModel.kt
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class HogeViewModel : ViewModel() {
private var _hoge: MutableLiveData<String>
var hoge: LiveData<String>
init {
_hoge = MutableLiveData<String>()
hoge = _hoge
}
fun changeHoge() {
_hoge.value = "test"
}
}
