我将自己放在从Java到Kotlin的RecycleView中。我正在尝试在屏幕旋转之间保持状态。但这是行不通的。这是我的代码:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
//import androidx.lifecycle.ViewModelProviders
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: ScoreViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProvider.NewInstanceFactory().create(ScoreViewModel::class.java)
//viewModel = ViewModelProviders.of(this).get(ScoreViewModel::class.java)
println("-> "+viewModel.scoreTeamA);
}
fun addOneForTeamA(view: View) {
viewModel.scoreTeamA++
displayForTeamA()
}
fun addTwoForTeamA(view: View) {
viewModel.scoreTeamA += 2
displayForTeamA()
}
fun addThreeForTeamA(view: View) {
viewModel.scoreTeamA += 3
displayForTeamA()
}
fun addOneForTeamB(view: View) {
++viewModel.scoreTeamB
displayForTeamB()
}
fun addTwoForTeamB(view: View) {
viewModel.scoreTeamB += 2
displayForTeamB()
}
fun addThreeForTeamB(view: View) {
viewModel.scoreTeamB += 3
displayForTeamB()
}
fun displayForTeamA(){
team_a_score.text = viewModel.scoreTeamA.toString()
}
fun displayForTeamB(){
team_b_score.text = viewModel.scoreTeamB.toString()
}
fun resetScore(view: View) {
viewModel.scoreTeamA = 0
viewModel.scoreTeamB = 0
displayForTeamA()
displayForTeamB()
}
}
import androidx.lifecycle.ViewModel
class ScoreViewModel : ViewModel() {
var scoreTeamA: Int = 0
var scoreTeamB: Int = 0
}
另一个问题是,为什么在一个项目中ViewModelProviders.of会被弃用(使用注释的行),而在另一个具有类似gradle依赖关系的项目中却可以。
谢谢!
答案 0 :(得分:2)
每次使用ViewModelProvider.NewInstanceFactory().create
都会创建一个新实例-这永远不是正确的选择。相反,请遵循ViewModelProviders.of() deprecation message:
使用
by viewModels()
Kotlin属性委托或ViewModelProvider(ViewModelStoreOwner)
来传递活动。
viewModel = new ViewModelProvider(this).get(ScoreViewModel::class.java)