【发布时间】:2020-12-07 21:19:19
【问题描述】:
随着kotlin synthetics 的弃用,我遇到了问题,我无法再从base class 访问一些标准布局。例如,我有一个用于三个片段的基类,并且在所有片段中都有一个按钮。我的旧方法是使用合成获取基类中的按钮,然后分配一些默认的 clicklistener 等。
我的问题是:从合成迁移到视图绑定/数据绑定的最佳方法是什么?我问自己的另一个问题是,我现在如何访问活动/片段之外的 view_layouts?
基类
abstract class BaseRebuildFragment(layout: Int) : Fragment(layout) {
abstract val nextFragment: NavDirections
abstract val baseViewModel: ViewModel
open val dataOverViewFragment: Boolean = false
@Inject @RebuildProgressDescription lateinit var progressBarDescription: ArrayList<String>
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initAppStandardToolbar()
initStateProgressBar(progressBarDescription)
initButton()
hideBottomNav()
}
private fun initButton() {
calibrate_btn_next.setOnClickListener { // not working anymore
if (dataOverViewFragment) return@setOnClickListener else if (this.validForm()) findNavController().navigate(nextFragment)
}
}
open fun validForm(): Boolean { return false }
}
片段
@AndroidEntryPoint
class RebuildOptionFragment : BaseRebuildFragment(R.layout.fragment_rebuild_option) {
override val baseViewModel: RebuildViewModel by navGraphViewModels(R.id.nav_send_rebuild) { defaultViewModelProviderFactory }
private val rebuildBinding: FragmentRebuildOptionBinding by viewBinding()
override val nextFragment: NavDirections = RebuildOptionFragmentDirections.actionRebuildOptionFragmentToRebuildUserDataFragment()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
bindObjects()
baseViewModel.setStateEvent(RebuildStateEvent.GetPrice)
subscribeRebuildListObserver()
}
private fun bindObjects() = with(rebuildBinding) {
viewModel = baseViewModel
lifecycleOwner = viewLifecycleOwner
lendingListener = LendingSwitch()
}
override fun validForm(): Boolean = baseViewModel.shippingValidator.isShippingOptionsValid()
}
在 utils 包中访问活动/片段之外的视图
fun Fragment.initStateProgressBar(progressBarDescription: ArrayList<String>) = with(app_standard_progress_bar) { // not working anymore
setStateDescriptionData(progressBarDescription)
}
fun Fragment.initAppStandardToolbar() {
toolbar.setupWithNavController(findNavController(), AppBarConfiguration(findNavController().graph)) // not working anymore
}
【问题讨论】:
标签: android kotlin kotlin-android-extensions