gpt4 book ai didi

java - 使用 View 模型将数据从 Activity 发送到 fragment

转载 作者:行者123 更新时间:2023-12-01 17:22:48 25 4
gpt4 key购买 nike

我正在尝试使用 fragment 而不是启动 Activity 来显示主要 Activity 中的数据。这是我的主要 Activity 屏幕

<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>

在我的主要 Activity 类(class)中,我有以下内容 私有(private)无效 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);
}
});
}

我的问题是如何开始在此处提交 fragment 并将 json 传递给 fragment 类我知道如何使用 Activity 执行此操作,但我想改用 fragment 。

我的 View 模型类

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.

在您的 fragment 中:

if (arguments != null)
String json = getArguments.getString(KEY, json)

希望这有帮助

关于java - 使用 View 模型将数据从 Activity 发送到 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61263152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com