发生点击事件时,使用MVVM添加片段

时间:2018-07-25 05:41:52

标签: android mvvm kotlin

使用MVVM体系结构和Fragment添加dataBinding的最佳方法是什么?

我想要的是单击按钮时替换或添加Fragment

我不确定我的方法是否正确。

我有 ActivityUtil 类,该类具有方法替换Fragment

 fun replaceFragmentToActivity(
    fragmentManager: FragmentManager?,
    fragment: Fragment,
    frameId: Int) {

checkNotNull(fragmentManager)
        .beginTransaction().apply {
            replace(frameId, fragment)
            addToBackStack(null)
            commit()
        }

interface ActivityHelper

interface ActivityHelper  {

fun replaceFragmentToActivity(fragment : Fragment)

}

MainFragment ActivityHelper interface的实现。

class MainFragment : Fragment(), ActivityHelper {
   override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false)

    binding.viewModel = ViewModelProviders.of(this)
            .get(MainFragmentViewModel::class.java)
            .apply {
                activityHelper = this@MainFragment
            }

 //call ActivityUtils's replaceFragmentToActivity.
  override fun replaceFragmentToActivity(fragment : Fragment) {
    replaceFragmentToActivity(
            activity?.supportFragmentManager,
            fragment,
            R.id.frame_main
    )
}

MainFragmentViewModel 在这里,调用ActivityHelper接口的replaceFragmentToActivity方法。

class MainFragmentViewModel : ViewModel() {

lateinit var activityHelper: ActivityHelper

//Check activityHelper is initialized.
private fun isActivityHelperInitialized() = (::activityHelper.isInitialized)

fun onFABClick(view: View) {
    if (isActivityHelperInitialized()) {
        when (view.id) {
            R.id.fab_wish -> activityHelper.replaceFragmentToActivity(WishFragment())

            R.id.fab_star -> activityHelper.replaceFragmentToActivity(StarFragment())

            R.id.fab_cmt -> activityHelper.replaceFragmentToActivity(CmtFragment())

        }
    }
}

fragment_main.xml ,其中包含三个浮动操作按钮。

  <com.github.clans.fab.FloatingActionButton
            android:id = "@+id/fab_wish"
            style = "@style/FABMain"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:onClick="@{viewModel::onFABClick}"
            />

   <com.github.clans.fab.FloatingActionButton
            android:id = "@+id/fab_star"
            style = "@style/FABMain"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:onClick="@{viewModel::onFABClick}"
            />

        <com.github.clans.fab.FloatingActionButton
            android:id = "@+id/fab_comment"
            style = "@style/FABMain"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:onClick="@{viewModel::onFABClick}"
            />

0 个答案:

没有答案