該建立好的都建立完成,接下來就是把他放到 Fragment 初始化,這樣就可以拿來存筆記內容啦
因為 NoteFragmentViewModelFactory、NoteFragmentViewModel,可能會比較佔資源,所以我們用lateinit
延遲初始化,binding
是自動產生的,可以不用理他
class NoteFragment : Fragment() {
private lateinit var binding: FragmentNoteBinding
private lateinit var viewModelFactory: NoteFragmentViewModelFactory
private lateinit var viewModel: NoteFragmentViewModel
}
有需要傳入 ViewModel 的東西,是先從 ViewModelFactory 傳入,再從 ViewModelFactory 帶到 ViewModel 內
class NoteFragment : Fragment() {
override fun onCreateView(
viewModelFactory = NoteFragmentViewModelFactory(傳入構造函數)
viewModel = ViewModelProvider(this, viewModelFactory)[NoteFragmentViewModel::class.java]
...
}
}
viewLifecycleOwner 會自己產生,綁定後就算螢幕轉動,資料也會留著
class NoteFragment : Fragment() {
override fun onCreateView(
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
}
class NoteFragment : Fragment() {
private lateinit var binding: FragmentNoteBinding
private lateinit var viewModelFactory: NoteFragmentViewModelFactory
private lateinit var viewModel: NoteFragmentViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = DataBindingUtil.inflate(
inflater,
R.layout.fragment_note,
container,
false
)
val application = requireNotNull(this.activity).application
viewModelFactory = NoteFragmentViewModelFactory()
viewModel = ViewModelProvider(this, viewModelFactory)[NoteFragmentViewModel::class.java]
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
}
onCreateView 負責把基本架構建立好,剩下的 TextView 那些就會在頁面建立完成後才初始化,也就是 onViewCreated
class NoteFragment : Fragment() {
private lateinit var binding: FragmentNoteBinding
private lateinit var viewModelFactory: NoteFragmentViewModelFactory
private lateinit var viewModel: NoteFragmentViewModel
override fun onCreateView(
...
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//TextView 初始化
}
}