[英]Send data to fragment from activity using viewmodels
我正在嘗試使用片段而不是啟動活動在我的主要活動中顯示我的數據。 這是我的主要活動屏幕
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBg"
tools:context=".ui.search.SearchActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/teamsRecyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/toolbar" />
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="130dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
在我的主要活動 class 我有以下 private void goToFragmentClass(Watch watch) {
Gson gson = new Gson();
viewModel.getTeamById(thisTeam.getTeamId()).observe(this, new Observer<Team>() {
String json = "";
@Override
public void onChanged(Team team) {
if (team != null)
json = gson.toJson(team);
else
json = gson.toJson(thisTeam);
//intent.putExtra("Watch", json);
// startActivity(intent);
}
});
}
我的問題是如何開始在此處提交片段並將json
傳遞給片段 class 我知道如何使用 Activity 來執行此操作,但我想改用片段。
我的視圖模型 class
public class SearchViewModel extends AndroidViewModel {
private MainRepository mainRepository;
public SearchViewModel(Application application) {
super(application);
mainRepository = new MainRepository(application);
}
LiveData<List<Team>> getTeamList(String teamName) {
return mainRepository.getTeamByName(teamName);
}
LiveData<Team> getTeamById(String id) {
return mainRepository.getTeam(id);
}
}
您可以使用 Bundle 將數據從 Activity 發送到 Fragment。
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString(KEY, json);
fragment.setArguments(bundle);
//Perform Fragment add/replace using fragment transaction here.
在你的片段中:
if (arguments != null)
String json = getArguments.getString(KEY, json)
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.