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