我正在使用 DataBinding
并遵循 MVVM 架构,现在我卡在了如何从 ViewModel
中添加新的 fragment,因为我们需要在 ViewModel
上定义点击事件。这是我的 MainViewModel
类:
public class MainViewModel {
private Context context;
public MainViewModel (Context context) {
this.context = context;
}
public void onClick(View v) {
}
}
这是我的XML文件,我在其中定义了点击事件:
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="viewmodel"
type="com.example.MainViewModel" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{viewmodel::onClick}"
android:text="click me"/>
</RelativeLayout>
</layout>
现在我该如何从我的ViewModel类中获取supportFragmentManager
或childFragmentManager
? 我已经尝试使用activity.getSupportFragmentManager()
和activity.getChildFragmentManager()
,但是它们没有这种方法。
我知道我们可以使用以下代码添加fragment:
getActivity().getSupportFragmentManager().beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out).
add(R.id.container, fragment, "").addToBackStack("main").commit();
但是在 ViewModel
类中如何实现呢?