我想开始每隔一秒增加一次计数。当我想使用方法 stopCount()
停止计数器时,我无法在 xml 中通过OnClick
调用它。
我收到此错误:
e: [kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
.
<data>
<variable name="mainViewModel" type="com.ali.mvvm_livedata.MainViewModel"/>
<variable name="count" type="String"/>
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@={mainViewModel.liveData}"
android:onClick="@{() -> mainViewModel.stopCount()}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@={mainViewModel.liveData}"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"/>
</android.support.constraint.ConstraintLayout>
这是我的观点模型
class MainViewModel : ViewModel() {
private val timer = Timer()
private lateinit var timmer: TimerTask
val liveData: MutableLiveData<String> = MutableLiveData()
fun getTime(): MutableLiveData<String> {
return liveData
}
fun count() {
var tempCount = 0
timmer = object : TimerTask() {
override fun run() {
tempCount++
Log.i("currentCount", tempCount.toString())
}
}
timer.scheduleAtFixedRate(timmer, 1000, 1000)
}
internal fun stopCount() {
timmer.cancel()
}
主活动代码
@Inject
lateinit var mModelFactory: ViewModelFactory
private lateinit var mainViewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
mainViewModel = ViewModelProviders.of(this, mModelFactory).get(MainViewModel::class.java)
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
binding.mainViewModel = mainViewModel
binding.lifecycleOwner = this
mainViewModel.count()
}
你必须删除内部(前面的乐趣停止计数(