当前位置:网站首页>Kotin fragment the correct way to get ViewModel instances
Kotin fragment the correct way to get ViewModel instances
2022-07-24 08:12:00 【White ceiceicei】
1. The first way to get it :
Usually get ViewModel Method :
val model : BlankViewModel by lazy{
ViewModelProvider(this,BlankViewModel.BlankViewModelFactory()).get(BlankViewModel::class.java)
}
// This method has been abandoned :viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
Corresponding BlankViewModelFactory Method
class BlankViewModel : ViewModel() {
// TODO: Implement the ViewModel
private val number = MutableLiveData<Int>();
private var i=0
fun getNumber() : LiveData<Int>{
return number
}
fun addNumber(){
i++
number.value = i
}
class BlankViewModelFactory(): ViewModelProvider.Factory{
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return BlankViewModel() as T
}
}
}
When we create Fragment page , And add the page to a Activity When in the page , Want to achieve in Activity Call in ViewModel The method in makes livedata Data changes , And hope Fragment The page can also listen for changes , At this point, you need to get the same ViewModel example , To ensure that the data of two pages changes at the same time .
First , stay Activity In order to get BlankViewModel , And call one of them by clicking the button addNumber Method , Let variables +1
class FragmentActivity : AppCompatActivity() {
val model : BlankViewModel by lazy{
ViewModelProvider(this,BlankViewModel.BlankViewModelFactory()).get(BlankViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fragment)
val button = findViewById<Button>(R.id.add).setOnClickListener {
model.addNumber()
}
}
}
first Fragment page :
class LeftFragment : Fragment() {
val model : BlankViewModel by lazy{
ViewModelProvider(requireActivity(),BlankViewModel.BlankViewModelFactory()).get(BlankViewModel::class.java)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.blank_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val left = view.findViewById<TextView>(R.id.left_tv)
model.getNumber().observe(requireActivity(), Observer {
Log.d("IT",""+it)
left.text = it.toString()
})
}
}
In obtaining ViewModel When an instance ,ViewModelProvider First parameter in ViewModelStoreOwner The object passes requireActivity Method , This method is to get the current Activity example ; If the position is still transmitted this , What we get is and Activity Different ViewModel example , such Activity When you click the button Fragment The value of the page does not change .
val model : BlankViewModel by lazy{
ViewModelProvider(requireActivity(),BlankViewModel.BlankViewModelFactory()).get(BlankViewModel::class.java)
}
In the way of observing change , The same is true :
model.getNumber().observe(requireActivity(), Observer {
left.text = it.toString()
})
the other one Fragment The page is the same as it , I don 't want to add .
2. The second way to get it
adopt ktx simplify :
add to ktx rely on , Note the version here , my kotlin Version is too low , Downloading a higher version will be red :
implementation "androidx.fragment:fragment-ktx:1.2.5"
implementation "androidx.activity:activity-ktx:1.0.0-alpha03"
stay Activity On the page :
// Other parts are omitted here
val model by viewModels<BlankViewModel>()
stay Fragment On the page
// Other parts are omitted here
val model by activityViewModels<BlankViewModel>()
// It can pass normally here this
model.getNumber().observe(this, Observer {
Log.d("IT",""+it)
left.text = it.toString()
})
The above is to get the same ViewModel Example method . If there is any wrong , Please correct me. .
边栏推荐
- Kotlin coroutine (II): scope and cancellation
- A Knight‘s Journey题解
- P1135 strange elevator problem solution
- 33 introduction to sparksql, dataframe and dataset
- Database system - Basic Concepts
- 图新地球:Revit建模的rvt格式BIM模型如何带着纹理精准匹配地图
- Debug No1 summarizes common solutions to bugs
- [interview] Why do you need foreach with the for cycle?
- About the big hole of wechat applet promise
- Error reported by Nacos: error Nacos failed to start, please see d:\nacos\logs\nacos log for more details.
猜你喜欢

Thesis reading: geotransformer
![[shutter] the shutter doctor reports an error](/img/09/20279b3ed71a18b28566ddbe212597.png)
[shutter] the shutter doctor reports an error

Why is knowledge base important? This is the best answer I've ever heard

Vidar-Team战队专访:AS WE DO, AS YOU KNOW.

OpenGL camera and periodic review

What is the NFT concept.. Fully understand NFT market, technology and cases

NFT是什么?一篇文章搞懂NFT的概念

Intelligent robots and intelligent systems (Professor Zheng Zheng of Dalian University of Technology) -- 1. robots and mobile robots

Full revolutionary Siamese networks for object tracking translation

Robot operation continuous learning thesis (1) original text reading and Translation -- primitive generation strategy learning without catastrophic forgetting in robot operation
随机推荐
What is the NFT concept.. Fully understand NFT market, technology and cases
Do you want to have a robot that can make cartoon avatars in three steps?
避坑,职场远离PUA,PUA常见的套路与话术你得了解一下!
JSON extractor use in JMeter
Full revolutionary Siamese networks for object tracking translation
Common DOS commands
Talk about compilers based on vscode
My six months at Microsoft
*Code understanding *numpy basic (plus code) that must be understood
Have you seen the interview questions of VR major? Trust me, it's absolutely useful
Learning dynamic Siamese network for visual object tracking full text translation
Uva572 oil deposits problem solution
Zhouzhihua machine learning watermelon book chapter 2 model evaluation and selection - accuracy and model generalization evaluation method, self-help method and integrated learning
Intelligent robots and intelligent systems (Professor Zheng Zheng of Dalian University of Technology) -- 1. robots and mobile robots
P1739 expression bracket matching problem solution
The vision group of Hegong University Sky team trained Day1 - machine learning, and learned to use the Yolo model
【线性代数】深入理解矩阵乘法、对称矩阵、正定矩阵
Robot operation continuous learning thesis (1) original text reading and Translation -- primitive generation strategy learning without catastrophic forgetting in robot operation
VIDAR team team exclusive interview: as we do, as you know
Digital twin demonstration project -- Talking about simple pendulum (4) IOT exploration