android - 在 MVVM 架构中从 ViewModel 添加 fragment

标签 android android-fragments mvvm android-databinding android-mvvm

我正在使用 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 类中获取 supportFragmentManagerchildFragmentManager?我尝试使用 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/

相关文章:

android - 如何在 Android 中从 Facebook 检索我的位置和电话号码?

android - 如何从 fragment 绑定(bind)服务

c# - 将参数传递给 ViewModel 构造函数

.net - 如何使用“交互行为”在不同控件之间移动焦点?

android - 如何获取设备 token

android - RelativeLayout 对齐父级 *side* + 边距 *side*

java - Android线程刚刚停止

java - 如何在android中的imageview上添加这个效果

java - Fragment : Setting the class variables vs putting the Bundle as arguments in the Fragment 的工厂方法

c# - 使用 MVVM 在 WPF 中绑定(bind)失败