LoginSignup
1
1

More than 3 years have passed since last update.

【Android/Kotlin】最小構成でLiveDataを使う

Last updated at Posted at 2021-01-09

環境

  • Mac
  • AndroidStudio4.1
  • Kotlin

LiveDataとは

データの変更をリアルタイムで検知して、それをトリガーとしてなんらかの処理を行う
LiveDataに検知したいデータを格納し、
Observerに変更された時の処理を記述する

結論

ソースコード全文 - Github

コード解説

今回のコードの動き

事前準備

  1. LiveDataを初期化
  2. Observerを定義

動かす

  1. 背景をタップする
  2. LiveDataの中身を変更する
  3. Observerが変更を検知し、text_viewsampleLiveDataの値を入れる

コード

build.gradle(app)
dependencies {
    // LiveData
    implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // LiveDataを初期化
        val sampleLiveData: MutableLiveData<LocalDateTime> by lazy {
            MutableLiveData<LocalDateTime>()
        }

        // Observerを定義
        // 3.sampleLiveData の値の変化を検知し、実行される
        sampleLiveData.observe(this, Observer { value ->
            // sampleLiveData.valueの値が変数valueに入っている
            value?.let { 
                text_view.text = it.toString() // text_viewにsampleLiveDataの内容を入れる
            }
        })

        // 1.背景タップ時
        constraint.setOnClickListener {
            // 2.sampleLiveDataに現在時刻を入れる
            sampleLiveData.value = LocalDateTime.now()
        }

    }
}

参考にした記事

LiveData の概要 - Android Developer

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1