使用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}"
/>