添加片段我使用DataBinding
及以下MVVM架构,现在我被困在如何从ViewModel
添加新的片段,因为我们需要对ViewModel
定义的点击事件我。这里是我MainViewModel
类从视图模型在MVVM架构
public class MainViewModel {
private Context context;
public MainViewModel (Context context) {
this.context = context;
}
public void onClick(View v) {
}
}
这是我在那里我已经定义click事件
<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
XML?我试图使用activity.getSupportFragmentManager()
和activity.getChildFragmentManager()
,但它没有这种方法。
我知道我们可以用下面的代码添加片段
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
类
是的,这是可用的方式,但我不确定在使用mvvm时这是否是个好主意。 –
我想用EventBus类型的想法,这是更好的解决方案,然后在这里接受的第一个答案。 – Jileshl
我想用EventBus类型的想法,这是更好的解决方案,然后在这里第一个接受的答案。 – Jileshl