進入Android Jetpack 架構,還是要提一下什麼是MVVM,再來使用ViewModel。
MVVM
View -------- View Model ------- Model
(Activity) (View Model) (DATA --- API , SQL...)
View
負責使用者介面,UI 層顯示,avtivity 和 fragment 都是
View Model
負責接受處理 View 的請求和回覆資料
Model
負責管理和更新資料,像是資料庫存取,API
如何使用 ViewModel
1.build.gradle (app):
dependencies {
….
//ViewModel
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
}
2.建立class 宣告續承 ViewModel():
class Day16ViewModel: ViewModel() {
init{ println("init Day16ViewModel")}
}
3. Activity 呼叫 ViewModel
class Day16Activity : AppCompatActivity() {
private lateinit var viewModel: Day16ViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_day16)
// Create a ViewModel the first time the system calls an activity's onCreate() method.
// Re-created activities receive the same Day16ViewModel instance created by the first activity.
// Use the 'by viewModels()' Kotlin property delegate
// from the activity-ktx artifact
viewModel = ViewModelProvider(this).get(Day16ViewModel::class.java)
….
}
}
4. Fragment呼叫 ViewModel:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Use the 'by activityViewModels()' Kotlin property delegate
// from the fragment-ktx artifact
val model: Day16ViewModel by activityViewModels()
}
5. 這樣就在activity 和 fragmnet 使用viewmodel 了
範例:
在 Activity 的 viewmodel 中設定字串為 “鐵人賽主題”,給Activity 和 fragment 的viewmodel 讀取字串顯示在畫面和log
執行結果:
https://developer.android.com/topic/libraries/architecture/viewmodel