簡體   English   中英

在MVVM架構中從ViewModel添加片段

[英]Add fragment from ViewModel in MVVM architecture

我正在使用DataBinding並遵循MVVM體系結構 ,現在我被困在如何從ViewModel添加新片段上,因為我們需要在ViewModel上定義click事件。 這是我的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()但是它沒有這種方法。

我知道我們可以使用以下代碼添加片段

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();
        }            
    }    
}

在調用任何方法之前,檢查上下文是您的活動的實例(例如MainActivity )還是AppCompatActivity ,或者它是否為null可能很有用。

我不知道是否可能,但這是我的建議:

定義一個接口,並讓Activity或Fragment實現此接口

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

將FragmentProvider的實例傳遞到您的ViewModel中

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(...);
   }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM