当前位置:网站首页>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. .
边栏推荐
- Continuous learning, lifelong learning, episodic memory, memory module paper summary -- gradient episodic memory promotes continuous learning
- P1305新二叉树题解
- [tools] a few lines of code can realize complex excel import and export tool classes, which is really strong!!!
- Have you seen the interview questions of VR major? Trust me, it's absolutely useful
- The vision group of Hegong University Sky team trained Day1 - machine learning, and learned to use the Yolo model
- [linear algebra] deeply understand matrix multiplication, symmetric matrix, positive definite matrix
- My six months at Microsoft
- Typescript double question mark operator
- When does MySQL use table locks and row locks?
- What is NFT? An article to understand the concept of NFT
猜你喜欢

Opencv project practice - credit card recognition

What is NFT? An article to understand the concept of NFT

Detailed notes on pytoch building neural network

Database system - Basic Concepts

NFT概念究竟是怎么回事。。全面了解NFT市场、技术和案例

13. Unity2d horizontal version of two-way platform that can move up, down, left and right (two-way walking + movable + independent judgment) + random platform generation

VIDAR team team exclusive interview: as we do, as you know

*Yolo5 learning * data experiment based on yolo5 face combined with attention model se

学习笔记总结篇(一)

Function analysis of e-commerce website development and construction
随机推荐
OpenGL camera and periodic review
Uva572 oil deposits problem solution
Debug No3 multi texture overlay
MySQL update uses case when to update the value of another field according to the value of one field
MySQL uses explain to analyze SQL execution plans to help find performance bottlenecks
Anaconda cannot shut down the method of forced shutdown
Decision tree - ID3, C4.5, cart
My six months at Microsoft
图的认识与存储
Perceptron and multilayer neural network, back propagation and computational graph
NFT概念究竟是怎么回事。。全面了解NFT市场、技术和案例
【MATLAB】(三)MATLAB在高等数学中的应用
Qt|字符串生成二维码功能
13. Unity2d horizontal version of two-way platform that can move up, down, left and right (two-way walking + movable + independent judgment) + random platform generation
图新地球:Revit建模的rvt格式BIM模型如何带着纹理精准匹配地图
Devops essay
nacos报错: ERROR Nacos failed to start, please see D:\nacos\logs\nacos.log for more details.
Kotlin coroutine (I): foundation and deepening
Upload and insert the execle table into the database based on ThinkPHP
[matlab] (III) application of MATLAB in Higher Mathematics