2

添加片段我使用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类supportFragmentManagerchildFragmentManager 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

回答

3

既然你有你的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(); 
     }    
    }  
} 

这可能是有用的,以检查是否上下文是您的活动的一个实例(如MainActivity)或AppCompatActivity,或者在调用任何方法之前是null

0

我不知道这是否是可能的,但这里是我的建议:

定义一个接口并让Activity或Fragment实现此接口

public interface FragmentProvider { 
    void showFragment(...); 
} 

传递FragmentProvider的实例到您的视图模型

public class MainViewModel { 
    private Context context; 
    private FragmentProvider provider; 

    public MainViewModel (FragmentProvider provider) { 
     this.provider = provider; 
    } 

    public void onClick(View v) { 
     // delegate the action 
     provider.showFragment(...); 
    } 

}

+0

是的,这是可用的方式,但我不确定在使用mvvm时这是否是个好主意。 –

+0

我想用EventBus类型的想法,这是更好的解决方案,然后在这里接受的第一个答案。 – Jileshl

+0

我想用EventBus类型的想法,这是更好的解决方案,然后在这里第一个接受的答案。 – Jileshl