如何通过viewModels实现



我一直在尝试实现LiveData和View模型。在这个应用程序中,屏幕上会显示一个数字,我们可以加五或减一。现在早些时候我使用了viewModelProvider,但现在它被弃用了,我使用的是"按视图模型",但它显示了一个错误

fragOne.kt

class fragOne : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
var binding = DataBindingUtil.inflate<FragmentFragoneBinding>(
inflater,
R.layout.fragment_fragone,
container,
false
)
//viewModel = ViewModelProviders.of(this).get(fragViewModel::class.java)
// Create the observer which updates the UI.
val viewModel: fragViewModel by **viewModels()**
val nameObserver = Observer<Int> {
viewModel.num.value=it
}
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
viewModel.num.observe(viewLifecycleOwner,nameObserver)
// setting on Click listener for add button
binding.add.setOnClickListener()
{
//updateNumber()
viewModel.num.setValue(viewModel.addFive())
}
// setting on on Click Listener for minus button
binding.minus.setOnClickListener()
{
viewModel.num.setValue(viewModel.minusOne())
//updateNumber()
}

return binding.root
}
// Always call the superclass so it can save the view hierarchy state
}

fragViewModel

import androidx.lifecycle.ViewModel
class fragViewModel:ViewModel()
{
val num: MutableLiveData<Int> by lazy {
MutableLiveData<Int>()
}
// Initializing num=0
init {
num .value= 0
}
// Functions to add five or subtract one
fun addFive():Int
{
var newNumber:Int?=num.value
return newNumber?.plus(5)?:0
}
fun minusOne():Int
{
var newNumber:Int?=num.value
return newNumber?.minus(1)?:0
}
}

fragOne中,viewModels在中显示了一个错误。那么错误是什么呢。请告诉我,如果有人想要代码,我会把它上传到Github

build.gradle

def lifecycle_version = "2.2.0"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation "androidx.core:core-ktx:1.2.0"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"

}

由于您在implementation "androidx.core:core-ktx:1.3.1"中使用了一个片段,因此将其添加到您的build.gradleimplementation "androidx.fragment:fragment-ktx:1.2.5"

片段中的用法

// Get a reference to the ViewModel scoped to this Fragment
val viewModel by viewModels<MyViewModel>()
// Get a reference to the ViewModel scoped to its Activity
val viewModel by activityViewModels<MyViewModel>()

首先添加以下依赖项以使用viewModels((,(最新版本(

implementation("androidx.navigation:navigation-fragment-ktx:$nav_version")
implementation("androidx.navigation:navigation-ui-ktx:$nav_version")
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"

然后你可以在你的碎片中使用

private val yourViewModel: YourViewModel by viewModels { // scope is this fragment      
YourViewModelFactory(YourRepository(YourItemDatabase.invoke(requireContext())))
}

private val yourViewModel: YourViewModel by activityViewModels()// scope is it's activity

相关内容

  • 没有找到相关文章

最新更新