我正在使用 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
类中做到这一点
最佳答案
因为您有可用的Context
,所以您有两种可能性:
public class MainViewModel {
private Context context;
public MainViewModel (Context context) {
this.context = context;
}
public void onClick(View v) {
//use context:
((AppCompatActivity) context).getSupportFragmentManager();
//OR use the views context:
if(v.getContext() instanceof AppCompatActivity) {
((AppCompatActivity) v.getContext()).getSupportFragmentManager();
}
}
}
检查上下文是否是您的 Activity 实例(如 MainActivity
)或 AppCompatActivity
,或者它是否为 null
可能很有用> 在调用任何方法之前。
关于android - 在 MVVM 架构中从 ViewModel 添加 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40086569/