有人可以建议我我的代码是对还是错?工作正常。 Kotlin每1秒观察一次实时数据
我尝试了此代码,并在android 6和9版中经过了良好的测试。
注意: ViewModel是一个类,负责为以下对象准备和管理数据 {@link android.app.Activity活动}或{@link androidx.fragment.app.Fragment片段}。 它还处理活动/片段与应用程序其余部分的通信 (例如,调用业务逻辑类)。
LiveDataViewModel.kt
package com.androidfeby.androidx.ui.livedata
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import java.text.SimpleDateFormat
import java.util.*
import androidx.core.os.HandlerCompat.postDelayed
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.os.Handler
class LiveDataViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
// handler every 1 sec delay
val h = Handler()
h.post(object : Runnable {
override fun run() {
// display date & time
val sdf = SimpleDateFormat("dd/M/yyyy hh:mm:ss", Locale.getDefault())
val currentDate = sdf.format(Date())
value = currentDate
h.postDelayed(this, 1000)
}
})
}
val text: LiveData<String> = _text
}
LiveDataFragment.kt
package com.androidfeby.androidx.ui.livedata
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.androidfeby.androidx.R
class LiveDataFragment : Fragment() {
private lateinit var liveDataViewModel: LiveDataViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
liveDataViewModel =
ViewModelProviders.of(this).get(LiveDataViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_live_data, container, false)
val textView: TextView = root.findViewById(R.id.text_date_time)
liveDataViewModel.text.observe(this, Observer {
textView.text = it
})
return root
}
}