我的應用程式應該能夠在來自 DialogFragment 的顏色選擇器的片段(稱為顏色預覽)中更改螢屏一部分的顏色,一旦單擊按鈕就會出現。我在 Fragment 和 DialogFragment 中使用了帶有 MutableLiveData 的相同 ViewModel。但是,當我在 DialogFragment 中選擇一些顏色時,我無法獲取有關 Fragment 中顏色的資料。代碼如下。
對話片段:
class ColorFragment : DialogFragment() {
private var _binding: FragmentColorBinding? = null
private val binding get() = _binding!!
private val viewModel: MainViewModel by lazy {
getViewModel {
MainViewModel()
}
}
@SuppressLint("DialogFragmentInsteadOfSimpleDialog")
override fun onStart() {
super.onStart()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
FragmentColorBinding.inflate(inflater, container, false).apply {
_binding = this
lifecycleOwner = this@ColorFragment
mainViewModel = getViewModel()
return root
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.color02.setOnClickListener {
viewModel.currentLightProfileColor.value = "#00ffff"
}
}
主要片段(應顯示顏色)如下所示:
class MainFragment : Fragment() {
private var _binding: FragmentMainBinding? = null
private val binding get() = _binding!!
private var viewCreated = false
private val viewModel: MainViewModel by lazy {
getViewModel {
MainViewModel()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
FragmentMainBinding.inflate(inflater, container, false).apply {
_binding = this
lifecycleOwner = this@MainFragment
mainViewModel = getViewModel()
executePendingBindings()
viewCreated = true
return root
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.colorPreview.holder?.addCallback(this)
viewModel.currentLightProfileColor.observe(viewLifecycleOwner) { color ->
Color.parseColor(color.toString()).let { color ->
Timber.d("color LiveDataGet: ${color}")
binding.colorPreview.setBackgroundColor(color)
}
}
binding.color.setOnClickListener {
findNavController().navigate(R.id.ColorFragment)
}
}
在我的 ViewModel 中,顏色只有 MutableLiveData:
class MainViewModel : ViewModel() {
val currentLightProfileColor = MutableLiveData<String>()}
我沒有收到任何錯誤,但是一旦我單擊 color2,我應該從 Timber in Log: "color LiveDataGet: #00ffff" 中得到,但我沒有,顏色預覽不會改變顏色。
我錯過了什么?如果有人可以快速查看我的代碼,我將不勝感激。謝謝!
uj5u.com熱心網友回復:
我找到了解決方案。在 Kotlin 中,如果在沒有 activityViewModels() 的情況下實體化 viewModels(),則不會共享資料。所以我改變了我的代碼,而不是:
private val viewModel: MainViewModel by lazy {
getViewModel {
LightmvpViewModel()
}
}
我寫:
private val viewModel: MainViewModel by activityViewModels()
通過這個簡單的更改,一切都應該正常。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/474133.html
標籤:安卓 科特林 安卓片段 android-dialogfragment 可变实时数据
上一篇:在片段中使用SwipeRefreshLayout滑動以重繪資料?
下一篇:方法可以自動訪問構建背景關系
